/**
 * Test Staff Login Flow
 * Simulates the login process to debug issues
 */

import { PrismaClient } from '../lib/generated/prisma/index.js';
import bcrypt from 'bcryptjs';

const prisma = new PrismaClient();

async function testLoginFlow() {
  console.log('\n🧪 Testing Staff Login Flow...\n');

  try {
    const username = 'asim';
    const password = 'AsimMawidi2025!';

    console.log(`1️⃣ Looking up user: "${username}"`);
    const user = await prisma.users.findUnique({
      where: { username },
    });

    if (!user) {
      console.log('❌ User not found!\n');
      return;
    }

    console.log('✅ User found');
    console.log(`   Role: ${user.role}`);
    console.log(`   Active: ${user.isActive}`);
    console.log(`   Locked: ${user.lockedUntil ? 'YES' : 'NO'}\n`);

    console.log(`2️⃣ Checking role...`);
    if (user.role === 'CUSTOMER') {
      console.log('❌ User has CUSTOMER role (not allowed for staff login)\n');
      return;
    }
    console.log(`✅ Role is ${user.role} (allowed)\n`);

    console.log(`3️⃣ Checking if account is active...`);
    if (!user.isActive) {
      console.log('❌ Account is inactive\n');
      return;
    }
    console.log('✅ Account is active\n');

    console.log(`4️⃣ Checking if account is locked...`);
    if (user.lockedUntil && new Date() < user.lockedUntil) {
      console.log(`❌ Account is locked until ${user.lockedUntil}\n`);
      return;
    }
    console.log('✅ Account is not locked\n');

    console.log(`5️⃣ Verifying password...`);
    if (!user.password) {
      console.log('❌ No password set on account\n');
      return;
    }

    const isValid = await bcrypt.compare(password, user.password);
    if (!isValid) {
      console.log('❌ Password does not match\n');
      return;
    }
    console.log('✅ Password is correct\n');

    console.log('🎉 ALL CHECKS PASSED!\n');
    console.log('The login should work. If you\'re seeing an error:');
    console.log('1. Check browser console for JavaScript errors');
    console.log('2. Check Network tab for failed requests');
    console.log('3. Try refreshing the page and logging in again');
    console.log('4. The CSRF error in server logs is a NextAuth quirk - login still works\n');

  } catch (error) {
    console.error('❌ Test failed:', error.message);
  } finally {
    await prisma.$disconnect();
  }
}

testLoginFlow();
