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");
};

// CREATE
router.post("/", async (req, res) => {
  const { employee_id, username, password, division_id, role_id } = req.body;
  try {
    // Hash the password before storing
    const hashedPassword = hashPassword(password);

    const [result] = await db.execute(
      "INSERT INTO users (employee_id, username, password, division_id, role_id) VALUES (?, ?, ?, ?, ?)",
      [employee_id, username, hashedPassword, division_id, role_id]
    );
    res.status(201).json({
      id: result.insertId,
      employee_id,
      username,
      division_id,
      role_id,
    });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// CHANGE PASSWORD (with verification)
router.post("/change-password", async (req, res) => {
  const { user_id, currentPassword, newPassword } = req.body;

  if (!user_id || !currentPassword || !newPassword) {
    return res.status(400).json({
      success: false,
      error: "User ID, current password, and new password are required",
    });
  }

  try {
    // Get user by user_id
    const [users] = await db.execute(
      "SELECT user_id, password FROM users WHERE user_id = ?",
      [user_id]
    );

    if (users.length === 0) {
      return res.status(404).json({
        success: false,
        error: "User not found",
      });
    }

    const user = users[0];

    // Hash the current password for comparison
    const hashedCurrentPassword = hashPassword(currentPassword);

    // Verify current password before allowing change
    if (user.password !== hashedCurrentPassword) {
      return res.status(401).json({
        success: false,
        error: "Current password is incorrect",
      });
    }

    // Hash the new password before storing
    const hashedNewPassword = hashPassword(newPassword);

    // Update the password
    const [result] = await db.execute(
      "UPDATE users SET password = ? WHERE user_id = ?",
      [hashedNewPassword, user.user_id]
    );

    if (result.affectedRows === 0) {
      return res.status(500).json({
        success: false,
        error: "Failed to update password",
      });
    }

    res.json({
      success: true,
      message: "Password changed successfully",
    });
  } catch (err) {
    console.error("Password change error:", err);
    res.status(500).json({
      success: false,
      error: "Internal server error during password change",
    });
  }
});

// READ ALL
router.get("/", async (req, res) => {
  try {
    const [rows] = await db.execute("SELECT * FROM users");
    res.json(rows);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// READ ONE
router.get("/:id", async (req, res) => {
  try {
    const [rows] = await db.execute("SELECT * FROM users WHERE user_id = ?", [
      req.params.id,
    ]);
    if (rows.length === 0) return res.status(404).json({ error: "Not found" });
    res.json(rows[0]);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// UPDATE
router.put("/:id", async (req, res) => {
  const { employee_id, username, password, division_id, role_id } = req.body;
  try {
    // Hash the password if it's being updated
    let hashedPassword = password;
    if (password) {
      hashedPassword = hashPassword(password);
    }

    const [result] = await db.execute(
      "UPDATE users SET employee_id = ?, username = ?, password = ?, division_id = ?, role_id = ? WHERE user_id = ?",
      [
        employee_id,
        username,
        hashedPassword,
        division_id,
        role_id,
        req.params.id,
      ]
    );
    if (result.affectedRows === 0)
      return res.status(404).json({ error: "Not found" });
    res.json({
      id: req.params.id,
      employee_id,
      username,
      division_id,
      role_id,
    });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// DELETE
router.delete("/:id", async (req, res) => {
  try {
    const [result] = await db.execute("DELETE FROM users WHERE user_id = ?", [
      req.params.id,
    ]);
    if (result.affectedRows === 0)
      return res.status(404).json({ error: "Not found" });
    res.json({ message: "Deleted" });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

module.exports = router;
