#!/usr/bin/env node
// Script to split name field in membership application JSON files under server/data/membership-applications/ (ESM)
// It will create backups for each modified file.

import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

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

const APPS_DIR = path.join(__dirname, '../server/data/membership-applications')

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(' ') }
}

function main() {
  if (!fs.existsSync(APPS_DIR)) {
    console.error('membership-applications Verzeichnis nicht gefunden:', APPS_DIR)
    process.exit(1)
  }

  const files = fs.readdirSync(APPS_DIR).filter(f => f.endsWith('.json'))
  if (files.length === 0) {
    console.log('Keine Bewerbungsdateien gefunden.')
    return
  }

  let modified = 0
  for (const file of files) {
    const p = path.join(APPS_DIR, file)
    let data
    try {
      data = JSON.parse(fs.readFileSync(p, 'utf8'))
    } catch (err) {
      console.error('Fehler beim Lesen von', p, err.message)
      continue
    }

    if ((!data.firstName || !data.lastName) && data.name) {
      const { firstName, lastName } = extractNames(data.name)
      data.firstName = data.firstName || firstName
      data.lastName = data.lastName || lastName

      // Backup
      const backup = p + '.bak'
      fs.copyFileSync(p, backup)
      fs.writeFileSync(p, JSON.stringify(data, null, 2))
      modified++
      console.log('Updated', p, '-> backup at', backup)
    }
  }

  console.log('Done. Modified files:', modified)
}

main()
