const express = require("express");
const router = express.Router();
const db = require("../db");
const crypto = require("crypto");

// Helper function to hash password with SHA2
const hashPassword = (password) => {
  return crypto.createHash("sha256").update(password).digest("hex");
};

router.post("/login", async (req, res) => {
  const { username, password } = req.body;

  if (!username || !password) {
    return res
      .status(400)
      .json({ error: "Username and password are required" });
  }

  try {
    // Temporary test login - accept any credentials
    if (username === "test" && password === "test") {
      // Return mock user data for testing
      res.json({
        message: "Login successful",
        user: {
          user_id: 1,
          username: "test",
          employee_name: "Test User",
          division: "IT",
          role: "Admin",
        },
      });
      return;
    }

    const [rows] = await db.execute(
      `SELECT 
         u.user_id, u.username, u.password, 
         e.employee_name, d.division_name, r.role_name
       FROM users u
       JOIN employees e ON u.employee_id = e.employee_id
       JOIN divisions d ON u.division_id = d.division_id
       JOIN roles r ON u.role_id = r.role_id
       WHERE u.username = ?`,
      [username]
    );

    if (rows.length === 0) {
      return res.status(401).json({ error: "Invalid username or password" });
    }

    const user = rows[0];

    // Hash the provided password with SHA2 and compare with stored hash
    const hashedPassword = hashPassword(password);
    const passwordMatch = hashedPassword === user.password;

    if (!passwordMatch) {
      return res.status(401).json({ error: "Invalid username or password" });
    }

    // Successful login
    res.json({
      message: "Login successful",
      user: {
        user_id: user.user_id,
        username: user.username,
        employee_name: user.employee_name,
        division: user.division_name,
        role: user.role_name,
      },
    });
  } catch (err) {
    console.error("Login error:", err);
    res.status(500).json({ error: "Server error" });
  }
});

module.exports = router;
