/**
 * Check Admin Account Details
 */

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

const prisma = new PrismaClient();

async function checkAdminAccount() {
  console.log('\n🔍 Checking Admin Account...\n');

  try {
    // Find the asim account
    const user = await prisma.users.findUnique({
      where: { username: 'asim' },
      select: {
        id: true,
        name: true,
        email: true,
        username: true,
        password: true,
        role: true,
        isActive: true,
        failedAttempts: true,
        lockedUntil: true,
        createdAt: true,
        lastLoginAt: true,
      },
    });

    if (!user) {
      console.log('❌ User "asim" not found in database!\n');
      console.log('Run: node scripts/create-asim-admin.mjs\n');
      return;
    }

    console.log('✅ Account Found:\n');
    console.log(`   ID: ${user.id}`);
    console.log(`   Name: ${user.name}`);
    console.log(`   Email: ${user.email}`);
    console.log(`   Username: ${user.username}`);
    console.log(`   Role: ${user.role}`);
    console.log(`   Active: ${user.isActive}`);
    console.log(`   Failed Attempts: ${user.failedAttempts}`);
    console.log(`   Locked Until: ${user.lockedUntil || 'Not locked'}`);
    console.log(`   Created: ${user.createdAt}`);
    console.log(`   Last Login: ${user.lastLoginAt || 'Never'}`);
    console.log(`   Password Hash: ${user.password ? 'Set (hash present)' : 'NOT SET'}\n`);

    // Test password verification
    if (user.password) {
      const testPassword = 'AsimMawidi2025!';
      console.log(`🔐 Testing password verification for: "${testPassword}"`);
      const isValid = await bcrypt.compare(testPassword, user.password);
      console.log(`   Password matches: ${isValid ? '✅ YES' : '❌ NO'}\n`);

      if (!isValid) {
        console.log('⚠️  Password does not match!');
        console.log('   The stored hash does not match the expected password.\n');
        console.log('💡 Solution: Delete and recreate the account:');
        console.log('   1. Delete: await prisma.users.delete({ where: { username: "asim" } })');
        console.log('   2. Recreate: node scripts/create-asim-admin.mjs\n');
      }
    }

    // Check if account is locked
    if (user.lockedUntil && new Date() < user.lockedUntil) {
      const remainingMinutes = Math.ceil((user.lockedUntil.getTime() - Date.now()) / (60 * 1000));
      console.log(`⚠️  Account is LOCKED for ${remainingMinutes} more minutes\n`);
      console.log('💡 To unlock manually:');
      console.log('   await prisma.users.update({');
      console.log('     where: { username: "asim" },');
      console.log('     data: { failedAttempts: 0, lockedUntil: null }');
      console.log('   })\n');
    }

    // Check role is staff/admin
    if (user.role === 'CUSTOMER') {
      console.log('❌ Account has CUSTOMER role, not staff!\n');
      console.log('💡 Fix: Update role to SUPER_ADMIN:');
      console.log('   await prisma.users.update({');
      console.log('     where: { username: "asim" },');
      console.log('     data: { role: "SUPER_ADMIN" }');
      console.log('   })\n');
    }

  } catch (error) {
    console.error('❌ Error checking account:', error.message);
  } finally {
    await prisma.$disconnect();
  }
}

checkAdminAccount();
