const CryptoJS = require('crypto-js')
const crypto = require('crypto')

const FIELD_ENCRYPTION_KEY = process.env.FIELD_ENCRYPTION_KEY || 'dev_field_key_change_in_production_32chars_min!'

function encrypt(text) {
  if (!text) return null
  try {
    return CryptoJS.AES.encrypt(text, FIELD_ENCRYPTION_KEY).toString()
  } catch (e) {
    return text
  }
}

function hash(text) {
  if (!text) return null
  return crypto.createHash('sha256').update(String(text).toLowerCase()).digest('hex')
}

module.exports.up = function up(db) {
  // Ensure users table has email_hash column
  try {
    db.exec('ALTER TABLE users ADD COLUMN email_hash TEXT')
  } catch {}
  // Populate encryption/hash where missing
  const users = db.prepare('SELECT id, email FROM users').all()
  const update = db.prepare('UPDATE users SET email = ?, email_hash = ? WHERE id = ?')
  const tx = db.transaction(() => {
    for (const u of users) {
      const hasEncryptedMarker = typeof u.email === 'string' && u.email.includes('U2FsdGVkX1')
      const plainEmail = u.email
      const encrypted = hasEncryptedMarker ? u.email : encrypt(plainEmail)
      const hashed = hash(plainEmail)
      update.run(encrypted, hashed, u.id)
    }
  })
  tx()
  // Add unique constraint index for email_hash if not exists
  try {
    db.exec('CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email_hash_unique ON users(email_hash)')
  } catch {}
}

