/**
 * Fix Staff Login Issues
 * - Creates staff user "asim" with proper credentials
 * - Verifies database connection
 * - Tests login functionality
 */

import bcrypt from 'bcryptjs';
import { prisma } from '../lib/db';
import { v4 as uuidv4 } from 'uuid';

async function fixStaffLogin() {
  console.log('🔧 Fixing Staff Login...\n');

  try {
    // Step 1: Verify database connection
    console.log('1️⃣ Verifying database connection...');
    await prisma.$connect();
    console.log('✅ Database connected\n');

    // Step 2: Check if user already exists
    console.log('2️⃣ Checking for existing user "asim"...');
    const existingUser = await prisma.users.findUnique({
      where: { username: 'asim' },
    });

    if (existingUser) {
      console.log('⚠️  User "asim" already exists!');
      console.log(`   ID: ${existingUser.id}`);
      console.log(`   Email: ${existingUser.email}`);
      console.log(`   Role: ${existingUser.role}`);
      console.log(`   Active: ${existingUser.isActive}`);

      const updateUser = process.argv.includes('--force');
      if (!updateUser) {
        console.log('\n✅ No action needed. Use --force to update existing user.');
        return;
      }

      console.log('\n🔄 Updating existing user...');
      const hashedPassword = await bcrypt.hash('AsimMawidi2025!', 12);

      await prisma.users.update({
        where: { id: existingUser.id },
        data: {
          password: hashedPassword,
          role: 'ADMIN',
          isActive: true,
          failedAttempts: 0,
          lockedUntil: null,
          updatedAt: new Date(),
        },
      });

      console.log('✅ User updated successfully\n');
    } else {
      // Step 3: Create new staff user
      console.log('3️⃣ Creating staff user "asim"...');

      const hashedPassword = await bcrypt.hash('AsimMawidi2025!', 12);
      console.log('   Password hashed with bcrypt (rounds=12)');

      const newUser = await prisma.users.create({
        data: {
          id: uuidv4(),
          email: 'asim@mawidi.com',
          name: 'Asim Mawidi',
          username: 'asim',
          password: hashedPassword,
          role: 'ADMIN',
          isActive: true,
          emailVerified: new Date(),
          createdAt: new Date(),
          updatedAt: new Date(),
          failedAttempts: 0,
          onboardingComplete: true,
        },
      });

      console.log('✅ Staff user created successfully!');
      console.log(`   ID: ${newUser.id}`);
      console.log(`   Email: ${newUser.email}`);
      console.log(`   Username: ${newUser.username}`);
      console.log(`   Role: ${newUser.role}\n`);
    }

    // Step 4: Verify user can be found
    console.log('4️⃣ Verifying user lookup...');
    const verifyUser = await prisma.users.findUnique({
      where: { username: 'asim' },
      select: {
        id: true,
        username: true,
        email: true,
        name: true,
        role: true,
        isActive: true,
        password: true,
      },
    });

    if (!verifyUser) {
      throw new Error('Failed to verify user creation');
    }

    console.log('✅ User lookup successful');
    console.log(`   Found: ${verifyUser.username} (${verifyUser.email})`);
    console.log(`   Role: ${verifyUser.role}`);
    console.log(`   Active: ${verifyUser.isActive}`);
    console.log(`   Has Password: ${verifyUser.password ? 'Yes' : 'No'}\n`);

    // Step 5: Test password verification
    console.log('5️⃣ Testing password verification...');
    const isPasswordValid = await bcrypt.compare('AsimMawidi2025!', verifyUser.password || '');

    if (isPasswordValid) {
      console.log('✅ Password verification successful\n');
    } else {
      console.log('❌ Password verification failed\n');
      throw new Error('Password verification failed');
    }

    // Success summary
    console.log('═══════════════════════════════════════════════════════════');
    console.log('✅ Staff Login Fix Complete!');
    console.log('═══════════════════════════════════════════════════════════');
    console.log('\n📋 Test Credentials:');
    console.log('   URL: http://localhost:9000/staff/login');
    console.log('   Username: asim');
    console.log('   Password: AsimMawidi2025!');
    console.log('\n🚀 Next Steps:');
    console.log('   1. Navigate to http://localhost:9000/staff/login');
    console.log('   2. Enter the credentials above');
    console.log('   3. Click "Sign In"');
    console.log('   4. You should be redirected to /staff/dashboard');
    console.log('\n');

  } catch (error) {
    console.error('\n❌ Error:', error);
    process.exit(1);
  } finally {
    await prisma.$disconnect();
  }
}

// Run the fix
fixStaffLogin();
