// Purge users from DB, keeping only 'admin' and a specific email
// Usage (from backend directory):
//   npm run purge-users -- --email someone@example.com

const path = require('path')
const fs = require('fs')
const Database = require('better-sqlite3')
const CryptoJS = require('crypto-js')

function getDbPath() {
  const envPath = process.env.DATABASE_PATH
  if (envPath && envPath.trim()) return envPath
  const prod = process.env.NODE_ENV === 'production'
  return prod
    ? path.join(process.cwd(), 'data', 'skillmate.encrypted.db')
    : path.join(process.cwd(), 'skillmate.dev.encrypted.db')
}

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

function parseEmailArg() {
  const idx = process.argv.indexOf('--email')
  if (idx !== -1 && process.argv[idx + 1]) return process.argv[idx + 1]
  return null
}

function backupFile(filePath) {
  try {
    const dir = path.dirname(filePath)
    const base = path.basename(filePath)
    const ts = new Date().toISOString().replace(/[:.]/g, '-').replace('T', '_').slice(0,19)
    const dest = path.join(dir, `${base}.backup_${ts}`)
    fs.copyFileSync(filePath, dest)
    console.log(`📦 Backup erstellt: ${dest}`)
  } catch (e) {
    console.warn('⚠️ Konnte kein Backup erstellen:', e.message)
  }
}

function main() {
  const dbPath = getDbPath()
  const keepEmail = parseEmailArg()
  if (!keepEmail) {
    console.error("❌ Bitte E-Mail angeben: --email someone@example.com")
    process.exit(1)
  }
  const keepHash = hashLower(keepEmail)

  console.log(`Datenbank: ${dbPath}`)
  console.log(`Behalte Nutzer: 'admin' und ${keepEmail}`)

  if (!fs.existsSync(dbPath)) {
    console.error('❌ Datenbankdatei nicht gefunden.')
    process.exit(1)
  }

  backupFile(dbPath)

  const db = new Database(dbPath)
  try {
    const all = db.prepare('SELECT id, username, email_hash FROM users').all()
    const keep = []
    const del = []
    for (const u of all) {
      if (u.username === 'admin') { keep.push(u); continue }
      if (u.email_hash && u.email_hash === keepHash) { keep.push(u); continue }
      del.push(u)
    }

    console.log(`Gefundene Nutzer: ${all.length}`)
    console.log(`Behalte: ${keep.length} | Lösche: ${del.length}`)

    const tx = db.transaction(() => {
      const delStmt = db.prepare('DELETE FROM users WHERE id = ?')
      for (const u of del) delStmt.run(u.id)
    })
    tx()

    console.log('✅ Bereinigung abgeschlossen.')
  } catch (err) {
    console.error('❌ Fehler bei der Bereinigung:', err)
    process.exitCode = 1
  } finally {
    db.close()
  }
}

main()

