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 createAdminUser() {
  try {
    console.log('Creating admin user...\n');

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

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

    if (existingAdmin) {
      console.log('Admin user already exists. Updating password and admin status...');
      await prisma.user.update({
        where: { email: 'admin@admin.com' },
        data: {
          passwordHash,
          isAdmin: true,
          name: 'Admin',
          hasWriteAccess: true, // Admins should have write access
        },
      });
      console.log('✅ Admin user updated');
    } else {
      console.log('Creating new admin user...');
      await prisma.user.create({
        data: {
          email: 'admin@admin.com',
          name: 'Admin',
          passwordHash,
          isAdmin: true,
          hasWriteAccess: true, // Admins should have write access
        },
      });
      console.log('✅ Admin user created');
    }

    console.log('\n✅ Admin user setup complete!');
    console.log('\nAdmin credentials:');
    console.log('  Email: admin@admin.com');
    console.log('  Password: admin');
    console.log('  Role: Admin (can approve identifications)');
  } catch (error: any) {
    console.error('Error creating admin user:', error);
    if (error.message.includes('permission denied')) {
      console.error('\n⚠️  Permission denied. Make sure:');
      console.error('  1. Database tables are created (run setup-auth-complete.sql)');
      console.error('  2. Database user has INSERT/UPDATE permissions on users table');
      console.error('  3. DATABASE_URL_AUTH is correctly configured in .env');
    }
    throw error;
  } finally {
    await prisma.$disconnect();
  }
}

createAdminUser();

