#!/usr/bin/env node
/**
 * Gibt einem bestehenden Benutzer zusaetzlich die Rolle "vorstand".
 *
 * Verwendung:
 *   node scripts/add-vorstand-role.js
 *   node scripts/add-vorstand-role.js <email>
 *
 * Standard-E-Mail:
 *   tsschulz@gmx.net
 */

import fs from 'fs/promises'
import path from 'path'
import { fileURLToPath } from 'url'
import dotenv from 'dotenv'
import { readUsers, writeUsers, migrateUserRoles } from '../server/utils/auth.js'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

dotenv.config({ path: path.join(__dirname, '..', '.env') })

const targetEmail = String(process.argv[2] || 'tsschulz@gmx.net').trim().toLowerCase()

function getUsersFilePath() {
  const cwd = process.cwd()
  if (cwd.endsWith('.output')) {
    return `${cwd}/../server/data/users.json`
  }
  return `${cwd}/server/data/users.json`
}

async function createBackup(filePath) {
  const backupDir = path.join(__dirname, '..', 'backups', `users-${Date.now()}`)
  await fs.mkdir(backupDir, { recursive: true })
  const backupPath = path.join(backupDir, 'users.json')
  await fs.copyFile(filePath, backupPath)
  return backupPath
}

async function main() {
  const usersFile = getUsersFilePath()

  console.log(`Suche Benutzer: ${targetEmail}`)

  const users = await readUsers()
  const user = users.find((entry) => String(entry.email || '').trim().toLowerCase() === targetEmail)

  if (!user) {
    console.error(`Benutzer nicht gefunden: ${targetEmail}`)
    process.exit(1)
  }

  migrateUserRoles(user)
  const currentRoles = Array.isArray(user.roles) ? [...user.roles] : []

  if (currentRoles.includes('vorstand')) {
    console.log(`Benutzer ${targetEmail} hat die Rolle "vorstand" bereits.`)
    console.log(`Aktuelle Rollen: ${currentRoles.join(', ')}`)
    return
  }

  const backupPath = await createBackup(usersFile)
  user.roles = [...new Set([...currentRoles, 'vorstand'])]

  const success = await writeUsers(users)
  if (!success) {
    console.error('Fehler beim Schreiben der Benutzerdaten.')
    process.exit(1)
  }

  console.log(`Backup erstellt: ${backupPath}`)
  console.log(`Rolle "vorstand" hinzugefuegt fuer ${targetEmail}`)
  console.log(`Aktuelle Rollen: ${user.roles.join(', ')}`)
}

main().catch((error) => {
  console.error('Fehler beim Hinzufuegen der Rolle "vorstand":', error)
  process.exit(1)
})
