/**
 * Test script to reproduce staff login error
 */
import { PrismaClient } from './lib/generated/prisma/index.js';
import bcrypt from 'bcryptjs';

const prisma = new PrismaClient({
  log: ['query', 'error', 'warn'],
});

async function testLogin() {
  try {
    console.log('Testing staff login...\n');

    // Find user
    console.log('1. Finding user by username...');
    const user = await prisma.user.findUnique({
      where: { username: 'asim' },
    });

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

    console.log('✅ User found:', {
      id: user.id,
      username: user.username,
      email: user.email,
      role: user.role,
      isActive: user.isActive,
      hasPassword: !!user.password,
    });

    // Test password
    if (user.password) {
      console.log('\n2. Testing password...');
      const isValid = await bcrypt.compare('AsimMawidi2025!', user.password);
      console.log(isValid ? '✅ Password matches' : '❌ Password does not match');
    }

    // Test audit log creation
    console.log('\n3. Testing audit log creation...');
    const testLog = await prisma.auditLog.create({
      data: {
        type: 'test_staff_login',
        action: 'Test login attempt',
        success: true,
        ip: '127.0.0.1',
        userAgent: 'test-script',
        metadata: { test: true },
      },
    });

    console.log('✅ Audit log created:', testLog.id);

    // Clean up test log
    await prisma.auditLog.delete({
      where: { id: testLog.id },
    });

    console.log('\n✅ All tests passed - login should work!');
  } catch (error) {
    console.error('\n❌ Error during test:', error);
    console.error('\nStack trace:', error.stack);
  } finally {
    await prisma.$disconnect();
  }
}

testLogin();
