#!/usr/bin/env node
import fs from 'fs'
import { promises as fsp } from 'fs'
import path from 'path'
import { readMembers, writeMembers } from '../server/utils/members.js'

// Script to split `name` into firstName/lastName for members.json.
// Usage:
//   node scripts/split-names-in-members.js        # dry-run, no writes
//   node scripts/split-names-in-members.js --apply  # apply changes and create backup

const MEMBERS_FILE_PATH = path.join(process.cwd(), 'server/data/members.json')

function extractNames(name) {
  if (!name || typeof name !== 'string') return { firstName: '', lastName: '' }
  const parts = name.trim().split(/\s+/)
  if (parts.length === 1) return { firstName: parts[0], lastName: '' }
  return { firstName: parts[0], lastName: parts.slice(1).join(' ') }
}

async function main() {
  const apply = process.argv.includes('--apply')

  console.log('Reading members via server utils (handles encryption)...')
  const members = await readMembers()
  if (!Array.isArray(members)) {
    console.error('Unerwartetes Format von members:', typeof members)
    process.exit(2)
  }

  let changed = false
  for (const m of members) {
    if ((!m.firstName || !m.lastName) && m.name) {
      const { firstName, lastName } = extractNames(m.name)
      if (!m.firstName) m.firstName = firstName
      if (!m.lastName) m.lastName = lastName
      changed = true
    }
  }

  if (!changed) {
    console.log('Keine Änderungen erforderlich. Alle Mitglieder haben firstName/lastName.')
    return
  }

  console.log(`Gefundene Änderungen: Mitglieder mit ergänztenn Namen werden ${apply ? 'angewendet' : 'nur angezeigt (dry-run)'}.`)

  if (!apply) {
    console.log('Vorschau der Änderungen (erstes 10 geänderte Mitglieder):')
    let count = 0
    for (const m of members) {
      if (m.firstName || m.lastName) {
        console.log('-', m.id || '(keine id)', m.firstName, m.lastName, '-', m.name)
        count++
        if (count >= 10) break
      }
    }
    console.log('\nFühre das Skript mit --apply aus, um die Änderungen dauerhaft zu schreiben (Backup wird erstellt).')
    return
  }

  // Create backup of raw file (may be encrypted)
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
  const backupPath = MEMBERS_FILE_PATH + `.bak.${timestamp}`
  try {
    await fsp.copyFile(MEMBERS_FILE_PATH, backupPath)
    console.log('Backup erstellt:', backupPath)
  } catch (err) {
    console.warn('Konnte kein Backup anlegen (Datei evtl. nicht vorhanden):', err.message)
  }

  // Write members using writeMembers (will handle encryption)
  await writeMembers(members)
  console.log('Mitglieder erfolgreich aktualisiert und verschlüsselt gespeichert.')
}

main().catch(err => {
  console.error('Fehler:', err)
  process.exit(1)
})
