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 make name column required (NOT NULL)...\n');

    // Check current state of the name column
    const columnInfo = await prisma.$queryRaw<Array<{
      column_name: string;
      data_type: string;
      is_nullable: string;
      column_default: string | null;
    }>>`
      SELECT column_name, data_type, is_nullable, column_default 
      FROM information_schema.columns 
      WHERE table_name = 'users' AND column_name = 'name';
    `;

    if (columnInfo.length === 0) {
      throw new Error('Name column not found in users table');
    }

    const currentState = columnInfo[0];
    console.log(`Current state: is_nullable = ${currentState.is_nullable}`);

    if (currentState.is_nullable === 'NO') {
      console.log('✅ Name column is already NOT NULL');
      return;
    }

    // Check if any users have NULL names
    const nullNameCount = await prisma.$queryRaw<Array<{count: bigint}>>`
      SELECT COUNT(*) as count FROM users WHERE name IS NULL;
    `;

    const count = Number(nullNameCount[0].count);
    if (count > 0) {
      console.log(`⚠️  Found ${count} user(s) with NULL names. Updating them to use email as name...`);
      await prisma.$executeRawUnsafe(`
        UPDATE users 
        SET name = email 
        WHERE name IS NULL;
      `);
      console.log('✅ Updated users with NULL names');
    }

    // Alter the column to be NOT NULL
    console.log('Altering name column to be NOT NULL...');
    await prisma.$executeRawUnsafe(`
      ALTER TABLE users 
      ALTER COLUMN name SET NOT NULL;
    `);
    console.log('✅ Column altered successfully');

    // Verify the change
    const verifyInfo = await prisma.$queryRaw<Array<{
      column_name: string;
      data_type: string;
      is_nullable: string;
      column_default: string | null;
    }>>`
      SELECT column_name, data_type, is_nullable, column_default 
      FROM information_schema.columns 
      WHERE table_name = 'users' AND column_name = 'name';
    `;

    const newState = verifyInfo[0];
    if (newState.is_nullable === 'NO') {
      console.log('\n✅ Migration completed successfully!');
      console.log('Name column is now required (NOT NULL).');
    } else {
      throw new Error('Migration failed: column is still nullable');
    }
  } catch (error: any) {
    console.error('\n❌ Migration failed:');
    console.error(error.message);
    if (error.code) {
      console.error(`Error code: ${error.code}`);
    }
    process.exit(1);
  } finally {
    await prisma.$disconnect();
  }
}

runMigration();

