// Run this from D:\panel\ with: node debug-login.js
require('dotenv').config();
const bcrypt = require('bcryptjs');
const fs     = require('fs');
const path   = require('path');

const DB = path.join(__dirname, 'data/users.json');

console.log('\n=== ServerPanel Login Debugger ===\n');

// 1. Check .env values
console.log('ADMIN_USER:      ', process.env.ADMIN_USER);
console.log('ADMIN_PASS_HASH: ', process.env.ADMIN_PASS_HASH ? process.env.ADMIN_PASS_HASH.substring(0,20) + '...' : '(not set)');
console.log('JWT_SECRET set:  ', !!process.env.JWT_SECRET);

// 2. Check users.json
console.log('\n--- users.json ---');
if (!fs.existsSync(DB)) {
  console.log('FILE MISSING — run the server once to create it');
} else {
  const users = JSON.parse(fs.readFileSync(DB, 'utf8'));
  console.log('Users found:', users.length);
  users.forEach(u => {
    console.log('\nUsername:   ', u.username);
    console.log('Role:       ', u.role);
    console.log('Hash prefix:', u.password ? u.password.substring(0, 20) + '...' : '(no password!)');

    // Test admin123 against stored hash
    const match123   = bcrypt.compareSync('admin123', u.password);
    const matchEnv   = process.env.ADMIN_PASS_HASH ? bcrypt.compareSync('admin123', process.env.ADMIN_PASS_HASH) : false;
    console.log('admin123 matches stored hash:', match123);
    console.log('admin123 matches .env hash:  ', matchEnv);
  });
}

// 3. Generate a fresh known-good hash
const freshHash = bcrypt.hashSync('admin123', 10);
console.log('\n--- Fresh hash for admin123 ---');
console.log(freshHash);
console.log('\nIf none of the above matched, replace the password field in data/users.json with the hash above.');