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

// Get encryption key from environment
const FIELD_ENCRYPTION_KEY = process.env.FIELD_ENCRYPTION_KEY || 'dev_field_key_change_in_production_32chars_min!';

// Encryption functions
function encrypt(text) {
  if (!text) return null;
  try {
    return CryptoJS.AES.encrypt(text, FIELD_ENCRYPTION_KEY).toString();
  } catch (error) {
    console.error('Encryption error:', error);
    return text;
  }
}

function isEncrypted(text) {
  // Check if text looks encrypted (AES encrypted strings start with 'U2FsdGVkX1')
  return text && text.includes('U2FsdGVkX1');
}

// Open database
const dbPath = path.join(__dirname, 'skillmate.dev.db');
console.log(`Opening database at: ${dbPath}`);
const db = new Database(dbPath);

try {
  console.log('\n=== Fixing User Email Encryption ===\n');
  
  // Get all users
  const users = db.prepare('SELECT id, username, email FROM users').all();
  console.log(`Found ${users.length} users`);
  
  let updatedCount = 0;
  for (const user of users) {
    // Skip if email is already encrypted
    if (isEncrypted(user.email)) {
      console.log(`✓ User ${user.username}: Email already encrypted`);
      continue;
    }
    
    // Skip if email is null
    if (!user.email) {
      console.log(`- User ${user.username}: No email to encrypt`);
      continue;
    }
    
    // Encrypt the email
    const encryptedEmail = encrypt(user.email);
    if (encryptedEmail && encryptedEmail !== user.email) {
      db.prepare('UPDATE users SET email = ? WHERE id = ?').run(encryptedEmail, user.id);
      console.log(`✓ User ${user.username}: Email encrypted successfully`);
      updatedCount++;
    } else {
      console.log(`✗ User ${user.username}: Failed to encrypt email`);
    }
  }
  
  console.log(`\n=== Summary ===`);
  console.log(`Total users: ${users.length}`);
  console.log(`Emails encrypted: ${updatedCount}`);
  console.log(`\n✓ Database encryption fix completed successfully!`);
  
} catch (error) {
  console.error('Error during encryption fix:', error);
  process.exit(1);
} finally {
  db.close();
}