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

const app = express();
app.use(express.json());

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

// Test login endpoint
app.post('/test-login', async (req, res) => {
  try {
    const { username, password } = req.body;
    console.log('=== TEST LOGIN ===');
    console.log('Username:', username);
    console.log('Password:', password);
    
    const dbPath = path.join(__dirname, 'skillmate.dev.db');
    const db = new Database(dbPath);
    
    // Find user by username
    const userRow = db.prepare(`
      SELECT id, username, email, password, role, employee_id, last_login, is_active, created_at, updated_at, email_hash
      FROM users
      WHERE username = ? AND is_active = 1
    `).get(username);
    
    console.log('User found:', !!userRow);
    if (userRow) {
      console.log('User details:', {
        id: userRow.id,
        username: userRow.username,
        email_hash: userRow.email_hash,
        is_active: userRow.is_active,
        password_hash: userRow.password ? userRow.password.substring(0, 20) + '...' : null
      });
      
      // Check password
      const isValidPassword = await bcryptjs.compare(password, userRow.password);
      console.log('Password valid:', isValidPassword);
      
      if (isValidPassword) {
        res.json({ success: true, message: 'Login successful!', user: { id: userRow.id, username: userRow.username } });
      } else {
        res.json({ success: false, message: 'Invalid password' });
      }
    } else {
      res.json({ success: false, message: 'User not found' });
    }
    
    db.close();
    
  } catch (error) {
    console.error('Test login error:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

app.listen(3005, () => {
  console.log('Test server running on port 3005');
  console.log('Test with: curl -X POST http://localhost:3005/test-login -H "Content-Type: application/json" -d "{\\"username\\":\\"admin\\",\\"password\\":\\"admin123\\"}"');
});