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

// Hash function for email
function hashEmail(email) {
  if (!email) return null;
  return crypto.createHash('sha256').update(email.toLowerCase()).digest('hex');
}

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

  try {
    console.log('\n=== Adding email_hash column to users table ===\n');
    
    // Check if column already exists
    const columns = db.prepare('PRAGMA table_info(users)').all();
    const hasEmailHash = columns.some(col => col.name === 'email_hash');
    
    if (!hasEmailHash) {
      console.log('Adding email_hash column...');
      db.prepare('ALTER TABLE users ADD COLUMN email_hash TEXT').run();
      
      // Update existing users with email hash
      const users = db.prepare('SELECT id, username, email FROM users').all();
      console.log(`Updating ${users.length} users with email hash...`);
      
      const updateStmt = db.prepare('UPDATE users SET email_hash = ? WHERE id = ?');
      for (const user of users) {
        // For admin user, we know the email
        if (user.username === 'admin') {
          const emailHash = hashEmail('admin@skillmate.local');
          updateStmt.run(emailHash, user.id);
          console.log(`Updated admin user with email hash`);
        }
      }
    } else {
      console.log('email_hash column already exists');
      
      // Make sure admin has the correct email_hash
      const adminEmail = 'admin@skillmate.local';
      const emailHash = hashEmail(adminEmail);
      
      console.log('Updating admin email_hash...');
      db.prepare('UPDATE users SET email_hash = ? WHERE username = ?').run(emailHash, 'admin');
    }
    
    console.log('\n✓ User table fixed successfully!');
    
  } catch (error) {
    console.error('Error fixing user table:', error);
    process.exit(1);
  } finally {
    db.close();
  }
}

// Run the fix
fixUserTable();