// Migrate users from legacy unencrypted DB (skillmate.dev.db)
// to encrypted dev DB (skillmate.dev.encrypted.db)
// Usage: from backend dir run: npm run migrate-users

const path = require('path')
const Database = require('better-sqlite3')
const CryptoJS = require('crypto-js')
require('dotenv').config()

function encKey() {
  return process.env.FIELD_ENCRYPTION_KEY || 'dev_field_key_change_in_production_32chars_min!'
}

function encrypt(text) {
  if (!text) return null
  return CryptoJS.AES.encrypt(text, encKey()).toString()
}

function sha256Lower(text) {
  return CryptoJS.SHA256((text || '').toLowerCase()).toString()
}

function main() {
  const legacyPath = path.join(process.cwd(), 'skillmate.dev.db')
  const encPath = path.join(process.cwd(), 'skillmate.dev.encrypted.db')

  const legacy = new Database(legacyPath)
  const enc = new Database(encPath)

  try {
    const legacyUsers = legacy.prepare('SELECT id, username, email, password, role, employee_id, last_login, is_active, created_at, updated_at FROM users').all()
    let migrated = 0
    const existsByUsername = enc.prepare('SELECT id FROM users WHERE username = ?')

    const insert = enc.prepare(`
      INSERT INTO users (id, username, email, email_hash, password, role, employee_id, last_login, is_active, created_at, updated_at)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `)

    for (const u of legacyUsers) {
      const exists = existsByUsername.get(u.username)
      if (exists) continue

      insert.run(
        u.id,
        u.username,
        encrypt(u.email),
        sha256Lower(u.email || ''),
        u.password,
        u.role,
        u.employee_id || null,
        u.last_login || null,
        u.is_active ?? 1,
        u.created_at || new Date().toISOString(),
        u.updated_at || new Date().toISOString()
      )
      migrated++
    }

    console.log(`✅ Migration abgeschlossen. Übertragene Benutzer: ${migrated}`)
  } catch (err) {
    console.error('❌ Migration fehlgeschlagen:', err)
    process.exitCode = 1
  } finally {
    legacy.close()
    enc.close()
  }
}

main()

