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

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

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

async function fixAdminUser() {
  try {
    console.log('Checking and fixing admin user...\n');

    // Check if has_write_access column exists by trying to query it
    let hasWriteAccessColumn = true;
    try {
      await prisma.$queryRaw`SELECT has_write_access FROM users LIMIT 1`;
      console.log('✅ has_write_access column exists');
    } catch (error: any) {
      if (error.message?.includes('has_write_access') || error.message?.includes('column') || error.code === '42703') {
        console.log('❌ has_write_access column does NOT exist');
        console.log('\n⚠️  You need to run the database migration first:');
        console.log('   psql -U postgres -d punimtag -f migrations/add-write-access-column.sql');
        console.log('\n   Or manually add the column:');
        console.log('   ALTER TABLE users ADD COLUMN has_write_access BOOLEAN NOT NULL DEFAULT false;');
        hasWriteAccessColumn = false;
      } else {
        throw error;
      }
    }

    if (!hasWriteAccessColumn) {
      console.log('\n⚠️  Please run the migration and then run this script again.');
      return;
    }

    // Hash the password
    const passwordHash = await bcrypt.hash('admin', 10);

    // Check if admin user exists
    const existingAdmin = await prisma.user.findUnique({
      where: { email: 'admin@admin.com' },
    });

    if (existingAdmin) {
      console.log('✅ Admin user found, updating...');
      await prisma.user.update({
        where: { email: 'admin@admin.com' },
        data: {
          passwordHash,
          isAdmin: true,
          name: 'Admin',
          hasWriteAccess: true,
        },
      });
      console.log('✅ Admin user updated successfully');
    } else {
      console.log('Creating new admin user...');
      await prisma.user.create({
        data: {
          email: 'admin@admin.com',
          name: 'Admin',
          passwordHash,
          isAdmin: true,
          hasWriteAccess: true,
        },
      });
      console.log('✅ Admin user created successfully');
    }

    // Verify the user
    const admin = await prisma.user.findUnique({
      where: { email: 'admin@admin.com' },
      select: {
        id: true,
        email: true,
        name: true,
        isAdmin: true,
        hasWriteAccess: true,
      },
    });

    console.log('\n✅ Admin user verified:');
    console.log('  Email:', admin?.email);
    console.log('  Name:', admin?.name);
    console.log('  Is Admin:', admin?.isAdmin);
    console.log('  Has Write Access:', admin?.hasWriteAccess);

    // Test password
    const testPassword = 'admin';
    const fullUser = await prisma.user.findUnique({
      where: { email: 'admin@admin.com' },
      select: { passwordHash: true },
    });
    
    if (fullUser) {
      const isValid = await bcrypt.compare(testPassword, fullUser.passwordHash);
      console.log('  Password test:', isValid ? '✅ VALID' : '❌ INVALID');
    }

    console.log('\n✅ Setup complete!');
    console.log('\nYou can now login with:');
    console.log('  Email: admin@admin.com');
    console.log('  Password: admin');
  } catch (error: any) {
    console.error('\n❌ Error:', error.message);
    if (error.message.includes('permission denied')) {
      console.error('\n⚠️  Permission denied. Make sure:');
      console.error('  1. Database tables are created');
      console.error('  2. Database user has INSERT/UPDATE permissions');
      console.error('  3. DATABASE_URL_AUTH is correctly configured in .env');
    } else if (error.message.includes('relation') || error.message.includes('does not exist')) {
      console.error('\n⚠️  Database tables may not exist. Run setup-auth-complete.sql first.');
    }
    throw error;
  } finally {
    await prisma.$disconnect();
  }
}

fixAdminUser();

