const Database = require('better-sqlite3');
const bcrypt = require('bcrypt');
const crypto = require('crypto');
const path = require('path');

// Hash function for email
function hashEmail(email) {
  if (!email) return null;
  return crypto.createHash('sha256').update(email.toLowerCase()).digest('hex');
}

async function testAuth() {
  const dbPath = path.join(__dirname, 'skillmate.dev.db');
  console.log(`Opening database at: ${dbPath}`);
  const db = new Database(dbPath);

  try {
    console.log('\n=== Testing Authentication ===\n');
    
    // Get admin user
    const adminUser = db.prepare('SELECT * FROM users WHERE username = ?').get('admin');
    
    if (adminUser) {
      console.log('Admin user found:');
      console.log('- ID:', adminUser.id);
      console.log('- Username:', adminUser.username);
      console.log('- Email (encrypted):', adminUser.email ? adminUser.email.substring(0, 20) + '...' : null);
      console.log('- Email hash:', adminUser.email_hash);
      console.log('- Role:', adminUser.role);
      console.log('- Is Active:', adminUser.is_active);
      
      // Test password
      const password = 'admin123';
      const isValidPassword = await bcrypt.compare(password, adminUser.password);
      console.log('\nPassword test (admin123):', isValidPassword ? 'PASS' : 'FAIL');
      
      // Check email hash
      const expectedEmailHash = hashEmail('admin@skillmate.local');
      console.log('\nExpected email hash:', expectedEmailHash);
      console.log('Actual email hash:', adminUser.email_hash);
      console.log('Email hash match:', adminUser.email_hash === expectedEmailHash ? 'PASS' : 'FAIL');
      
      // Test email login
      const emailHash = hashEmail('admin@skillmate.local');
      const userByEmail = db.prepare('SELECT * FROM users WHERE email_hash = ? AND is_active = 1').get(emailHash);
      console.log('\nEmail login test:', userByEmail ? 'User found' : 'User NOT found');
      
      // Test username login
      const userByUsername = db.prepare('SELECT * FROM users WHERE username = ? AND is_active = 1').get('admin');
      console.log('Username login test:', userByUsername ? 'User found' : 'User NOT found');
      
    } else {
      console.log('Admin user not found!');
    }
    
    console.log('\n=== Test complete ===');
    
  } catch (error) {
    console.error('Error testing auth:', error);
    process.exit(1);
  } finally {
    db.close();
  }
}

// Run the test
testAuth();