const express = require("express");
const bcrypt = require("bcrypt");
const { query } = require("./config/database");

async function testLogin() {
  const email = "admin@example.com";
  const password = "Admin123";

  try {
    console.log("1. Querying database for user...");
    const result = await query(
      "SELECT id, email, name, passwordhash, role FROM adminusers WHERE email = $1",
      [email]
    );

    if (result.rows.length === 0) {
      console.log("❌ User not found");
      return;
    }

    console.log("2. User found:", result.rows[0].email);

    const admin = result.rows[0];
    console.log("3. Comparing password...");
    const validPassword = await bcrypt.compare(password, admin.passwordhash);

    if (!validPassword) {
      console.log("❌ Invalid password");
      return;
    }

    console.log("4. ✓ Password valid!");

    console.log("5. Updating last login...");
    await query("UPDATE adminusers SET lastlogin = NOW() WHERE id = $1", [
      admin.id,
    ]);

    console.log("6. ✓ Login successful!");
    console.log("   User ID:", admin.id);
    console.log("   Email:", admin.email);
    console.log("   Name:", admin.name);
    console.log("   Role:", admin.role);
  } catch (error) {
    console.error("❌ Error during login:", error.message);
    console.error("   Stack:", error.stack);
  }

  process.exit(0);
}

testLogin();
