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 checkAdminUser() {
  try {
    console.log('Checking admin user...\n');
    if (process.env.DATABASE_URL_AUTH) {
      // Mask password in connection string for display
      const masked = process.env.DATABASE_URL_AUTH.replace(/:([^:@]+)@/, ':****@');
      console.log('DATABASE_URL_AUTH:', masked);
      
      // Check if it has placeholder values
      if (process.env.DATABASE_URL_AUTH.includes('username') || process.env.DATABASE_URL_AUTH.includes('password')) {
        console.log('\n⚠️  WARNING: DATABASE_URL_AUTH contains placeholder values!');
        console.log('Please update .env file with actual database credentials.');
        console.log('Format: DATABASE_URL_AUTH="postgresql://actual_username:actual_password@localhost:5432/punimtag_auth"');
        return;
      }
    } else {
      console.log('DATABASE_URL_AUTH: NOT SET');
      console.log('Please add DATABASE_URL_AUTH to your .env file');
      return;
    }
    console.log('');

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

    if (!user) {
      console.log('❌ Admin user NOT FOUND');
      console.log('\nRun: npx tsx scripts/create-admin-user.ts');
      return;
    }

    console.log('✅ Admin user found:');
    console.log('  ID:', user.id);
    console.log('  Email:', user.email);
    console.log('  Name:', user.name);
    console.log('  Is Admin:', user.isAdmin);
    console.log('  Password Hash:', user.passwordHash.substring(0, 20) + '...');

    // Test password
    const testPassword = 'admin';
    const isValid = await bcrypt.compare(testPassword, user.passwordHash);
    console.log('\nPassword test:');
    console.log('  Testing password "admin":', isValid ? '✅ VALID' : '❌ INVALID');

    if (!isValid) {
      console.log('\n⚠️  Password hash does not match. Recreating admin user...');
      const newHash = await bcrypt.hash('admin', 10);
      await prisma.user.update({
        where: { email: 'admin@admin.com' },
        data: {
          passwordHash: newHash,
          isAdmin: true,
        },
      });
      console.log('✅ Admin user password updated');
    }
  } catch (error: any) {
    console.error('Error:', error.message);
    if (error.message.includes('P1001')) {
      console.error('\n⚠️  Cannot connect to database. Check DATABASE_URL_AUTH in .env');
    }
  } finally {
    await prisma.$disconnect();
  }
}

checkAdminUser();

