import { PrismaClient as PrismaClientAuth } from '../node_modules/.prisma/client-auth';
import * as fs from 'fs';
import * as path from 'path';

const prismaAuth = new PrismaClientAuth({
  datasourceUrl: process.env.DATABASE_URL_AUTH,
});

async function runMigration() {
  try {
    console.log('🔄 Running email verification migration...');
    console.log('📝 Reading migration file...');
    
    const migrationPath = path.join(__dirname, '../migrations/add-email-verification-columns.sql');
    const migrationSQL = fs.readFileSync(migrationPath, 'utf-8');
    
    // Execute each SQL statement individually
    const statements = [
      `ALTER TABLE users ADD COLUMN IF NOT EXISTS email_verified BOOLEAN NOT NULL DEFAULT true;`,
      `ALTER TABLE users ADD COLUMN IF NOT EXISTS email_confirmation_token VARCHAR(255) UNIQUE;`,
      `ALTER TABLE users ADD COLUMN IF NOT EXISTS email_confirmation_token_expiry TIMESTAMP;`,
      `CREATE INDEX IF NOT EXISTS idx_users_email_confirmation_token ON users(email_confirmation_token);`,
      `UPDATE users SET email_verified = true WHERE email_confirmation_token IS NULL;`,
    ];
    
    console.log(`📋 Executing ${statements.length} SQL statements...`);
    
    for (let i = 0; i < statements.length; i++) {
      const statement = statements[i];
      try {
        await prismaAuth.$executeRawUnsafe(statement);
        const desc = statement.split(' ').slice(0, 4).join(' ').toLowerCase();
        console.log(`✅ [${i + 1}/${statements.length}] ${desc}...`);
      } catch (error: any) {
        // Ignore "already exists" errors
        if (error.message?.includes('already exists') || 
            error.message?.includes('duplicate') ||
            error.message?.includes('IF NOT EXISTS')) {
          const desc = statement.split(' ').slice(0, 4).join(' ').toLowerCase();
          console.log(`ℹ️  [${i + 1}/${statements.length}] ${desc}... (already exists)`);
        } else {
          console.error(`❌ Error executing statement ${i + 1}:`, error.message);
          throw error;
        }
      }
    }
    
    console.log('✅ Migration completed successfully!');
    console.log('');
    console.log('📊 Verifying migration...');
    
    // Verify the columns were added
    const result = await prismaAuth.$queryRawUnsafe<Array<{column_name: string}>>(`
      SELECT column_name 
      FROM information_schema.columns 
      WHERE table_name = 'users' 
      AND column_name IN ('email_verified', 'email_confirmation_token', 'email_confirmation_token_expiry')
      ORDER BY column_name;
    `);
    
    console.log('✅ Found columns:', result.map(r => r.column_name).join(', '));
    
    // Check existing users
    const userCount = await prismaAuth.user.count();
    const verifiedCount = await prismaAuth.user.count({
      where: { emailVerified: true }
    });
    
    console.log(`📊 Users: ${userCount} total, ${verifiedCount} verified`);
    
  } catch (error: any) {
    console.error('❌ Migration failed:', error.message);
    process.exit(1);
  } finally {
    await prismaAuth.$disconnect();
  }
}

runMigration();

