const bcrypt = require('bcryptjs');
const db = require('./config/database');
const { decryptPassword } = require('./utils/crypto');

async function debugLogin() {
  try {
    console.log('=== LOGIN DEBUG ===');
    
    // Check if school user exists
    const [users] = await db.execute('SELECT * FROM users WHERE email = ? AND user_type = ?', ['school@test.com', 'school']);
    console.log('Users found:', users.length);
    
    if (users.length > 0) {
      const user = users[0];
      console.log('User details:', {
        id: user.id,
        email: user.email,
        user_type: user.user_type,
        password_hash: user.password_hash
      });
      
      // Test password comparison
      const plainPassword = 'school123';
      const base64Password = Buffer.from(plainPassword).toString('base64');
      
      console.log('Plain password:', plainPassword);
      console.log('Base64 password:', base64Password);
      console.log('Decrypted base64:', decryptPassword(base64Password));
      
      // Test both scenarios
      const directMatch = await bcrypt.compare(plainPassword, user.password_hash);
      const decryptedMatch = await bcrypt.compare(decryptPassword(base64Password), user.password_hash);
      
      console.log('Direct password match:', directMatch);
      console.log('Decrypted password match:', decryptedMatch);
      
    } else {
      console.log('No school user found! Creating one...');
      
      // Create school user
      const hashedPassword = await bcrypt.hash('school123', 10);
      await db.execute(`
        INSERT INTO users (username, email, password_hash, first_name, last_name, user_type, phone) 
        VALUES (?, ?, ?, ?, ?, ?, ?)
      `, ['schooladmin', 'school@test.com', hashedPassword, 'School', 'Admin', 'school', '555-0123']);
      
      console.log('School user created successfully!');
    }
    
  } catch (error) {
    console.error('Debug error:', error);
  } finally {
    process.exit();
  }
}

debugLogin();