#!/usr/bin/env node
// Script: split-names-in-users.js (ESM)
// Splittet das Feld "name" in firstName und lastName für alle User in users.json, falls noch nicht vorhanden.
// Backup wird automatisch angelegt.

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

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

const usersPath = path.join(__dirname, '../server/data/users.json')
const backupPath = usersPath + '.bak.' + new Date().toISOString().replace(/[:.]/g, '-')

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(usersPath)) {
    console.error('users.json nicht gefunden:', usersPath)
    process.exit(1)
  }
  const users = JSON.parse(fs.readFileSync(usersPath, 'utf8'))
  let changed = false

  for (const user of users) {
    if ((!user.firstName || !user.lastName) && user.name) {
      const { firstName, lastName } = extractNames(user.name)
      if (!user.firstName) user.firstName = firstName
      if (!user.lastName) user.lastName = lastName
      changed = true
    }
  }

  if (changed) {
    fs.copyFileSync(usersPath, backupPath)
    fs.writeFileSync(usersPath, JSON.stringify(users, null, 2))
    console.log('Felder firstName/lastName ergänzt. Backup:', backupPath)
  } else {
    console.log('Keine Änderungen nötig. Alle Namen bereits gesplittet.')
  }
}

main()
