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' });

// Connect to auth database
const dbUrl = process.env.DATABASE_URL_AUTH;
console.log(`Connecting to auth database: ${dbUrl ? dbUrl.replace(/:[^:@]+@/, ':****@') : 'none'}\n`);

const prisma = new PrismaClientAuth({
  datasourceUrl: dbUrl,
});

async function setupDatabase() {
  try {
    console.log('Setting up database tables and admin user...\n');

    // Test connection first
    await prisma.$connect();
    console.log('✅ Connected to auth database\n');

    // Create users table
    console.log('Creating users table...');
    await prisma.$executeRawUnsafe(`
      CREATE TABLE IF NOT EXISTS users (
        id SERIAL PRIMARY KEY,
        email VARCHAR(255) UNIQUE NOT NULL,
        name VARCHAR(255),
        password_hash VARCHAR(255) NOT NULL,
        is_admin BOOLEAN DEFAULT FALSE,
        is_active BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      );
    `);
    console.log('✅ Users table created');

    // Create pending_identifications table
    console.log('Creating pending_identifications table...');
    await prisma.$executeRawUnsafe(`
      CREATE TABLE IF NOT EXISTS pending_identifications (
        id SERIAL PRIMARY KEY,
        face_id INTEGER NOT NULL,
        user_id INTEGER NOT NULL,
        first_name VARCHAR(255) NOT NULL,
        last_name VARCHAR(255) NOT NULL,
        middle_name VARCHAR(255),
        maiden_name VARCHAR(255),
        date_of_birth DATE,
        status VARCHAR(50) DEFAULT 'pending',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
        -- Note: face_id references faces in punimtag database, but we can't use foreign key across databases
      );
    `);
    console.log('✅ Pending identifications table created');

    // Create indexes
    console.log('Creating indexes...');
    await prisma.$executeRawUnsafe(`
      CREATE INDEX IF NOT EXISTS idx_pending_identifications_face_id ON pending_identifications(face_id);
      CREATE INDEX IF NOT EXISTS idx_pending_identifications_user_id ON pending_identifications(user_id);
      CREATE INDEX IF NOT EXISTS idx_pending_identifications_status ON pending_identifications(status);
    `);
    console.log('✅ Indexes created');

    // Create admin user
    console.log('\nCreating admin user...');
    const passwordHash = await bcrypt.hash('admin', 10);
    
    const existingAdmin = await prisma.user.findUnique({
      where: { email: 'admin@admin.com' },
    });

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

    console.log('\n🎉 Database setup complete!');
    console.log('\nAdmin credentials:');
    console.log('  Email: admin@admin.com');
    console.log('  Password: admin');
    console.log('  Role: Admin');
  } catch (error: any) {
    console.error('\n❌ Error setting up database:', error.message);
    if (error.message.includes('permission denied')) {
      console.error('\n⚠️  Permission denied. You may need to:');
      console.error('  1. Run this script with a user that has CREATE TABLE permissions');
      console.error('  2. Or manually create the tables using setup-auth-complete.sql');
    } else if (error.message.includes('Authentication failed')) {
      console.error('\n⚠️  Authentication failed. Please check:');
      console.error('  1. DATABASE_URL_AUTH in .env file');
      console.error('  2. Database credentials are correct');
      console.error('  3. Database server is running');
    }
    process.exit(1);
  } finally {
    await prisma.$disconnect();
  }
}

setupDatabase();

