// Reset the admin login to username 'admin' with password 'admin123'
// Usage: from backend directory, run `npm run reset-admin` or `node scripts/reset-admin.js`

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

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 getFieldKey() {
  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, getFieldKey()).toString()
}

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

async function main() {
  const dbPath = getDbPath()
  console.log(`Using database: ${dbPath}`)
  const db = new Database(dbPath)

  try {
    const admin = db.prepare('SELECT id, username FROM users WHERE username = ?').get('admin')
    const newHash = await bcrypt.hash('admin123', 12)

    if (admin) {
      db.prepare('UPDATE users SET password = ?, is_active = 1, role = ?, updated_at = ? WHERE id = ?')
        .run(newHash, 'admin', new Date().toISOString(), admin.id)
      console.log('✅ Admin-Passwort zurückgesetzt: admin / admin123')
    } else {
      const now = new Date().toISOString()
      const email = 'admin@skillmate.local'
      db.prepare(`
        INSERT INTO users (id, username, email, email_hash, password, role, is_active, created_at, updated_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
      `).run(
        'admin-' + Date.now(),
        'admin',
        encrypt(email),
        sha256Lower(email),
        newHash,
        'admin',
        1,
        now,
        now
      )
      console.log('✅ Admin-Benutzer erstellt: admin / admin123')
    }
  } catch (err) {
    console.error('❌ Fehler beim Zurücksetzen der Admin-Anmeldeinformationen:', err)
    process.exitCode = 1
  } finally {
    db.close()
  }
}

main()

