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

// Load environment variables
dotenv.config({ path: '.env' });

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

async function runMigration() {
  try {
    console.log('Running migration to add has_write_access column...\n');

    // Check if column already exists
    try {
      await prisma.$queryRaw`SELECT has_write_access FROM users LIMIT 1`;
      console.log('✅ Column has_write_access already exists');
      return;
    } catch (error: any) {
      if (error.message?.includes('has_write_access') || error.code === '42703') {
        console.log('Column does not exist, adding it...');
      } else {
        throw error;
      }
    }

    // Add the column
    console.log('Adding has_write_access column...');
    await prisma.$executeRawUnsafe(`
      ALTER TABLE users 
      ADD COLUMN IF NOT EXISTS has_write_access BOOLEAN NOT NULL DEFAULT false;
    `);
    console.log('✅ Column added');

    // Create index
    console.log('Creating index...');
    await prisma.$executeRawUnsafe(`
      CREATE INDEX IF NOT EXISTS idx_users_has_write_access ON users(has_write_access);
    `);
    console.log('✅ Index created');

    // Update existing users to have write access = false (except we'll update admin separately)
    console.log('Updating existing users...');
    await prisma.$executeRawUnsafe(`
      UPDATE users 
      SET has_write_access = false 
      WHERE has_write_access IS NULL;
    `);
    console.log('✅ Existing users updated');

    // Verify
    const result = await prisma.$queryRaw<Array<{column_name: string, data_type: string, column_default: string}>>`
      SELECT column_name, data_type, column_default 
      FROM information_schema.columns 
      WHERE table_name = 'users' AND column_name = 'has_write_access';
    `;

    if (result.length > 0) {
      console.log('\n✅ Migration completed successfully!');
      console.log('Column details:', result[0]);
    } else {
      console.log('\n⚠️  Column was added but verification query returned no results');
    }
  } catch (error: any) {
    console.error('\n❌ Error running migration:', error.message);
    if (error.message.includes('permission denied')) {
      console.error('\n⚠️  Permission denied. You may need to run this as a database superuser.');
      console.error('Try running the SQL manually:');
      console.error('  ALTER TABLE users ADD COLUMN IF NOT EXISTS has_write_access BOOLEAN NOT NULL DEFAULT false;');
    }
    throw error;
  } finally {
    await prisma.$disconnect();
  }
}

runMigration();

