import bcrypt from "bcryptjs";
import { getDb } from "../config/db.js";
import { logAction } from "../utils/audit.helper.js";

export const listStaff = async (req, res) => {
  const db = getDb();
  const notaryId = req.user.notary_id;
  
  if (!notaryId) {
    return res.json([]);
  }

  const [rows] = await db.execute(
    "SELECT id, name, email, role, is_active, staff_id_code FROM users WHERE notary_id = ? AND role IN ('teller', 'payment', 'executive')",
    [notaryId]
  );
  res.json(rows);
};

export const createStaff = async (req, res) => {
  const db = getDb();
  const { name, email, role } = req.body;
  const notaryId = req.user.notary_id;

  if (!notaryId) {
    return res.status(403).json({ message: "Only notary owners can create staff" });
  }

  const tempPassword = Math.random().toString(36).slice(-8);
  const passwordHash = await bcrypt.hash(tempPassword, 10);
  
  // Generate a staff ID code
  const [[maxRow]] = await db.execute("SELECT MAX(id) as maxId FROM users");
  const nextId = (maxRow.maxId || 0) + 1;
  const staffIdCode = `NESOS-${new Date().getFullYear()}-${String(nextId).padStart(4, '0')}`;

  const [result] = await db.execute(
    `INSERT INTO users (notary_id, name, email, password_hash, role, staff_id_code, password_must_change)
     VALUES (?, ?, ?, ?, ?, ?, 1)`,
    [notaryId, name, email, passwordHash, role, staffIdCode]
  );

  await logAction(req.user.id, "CREATE_STAFF", `Created staff member: ${name} (${role})`);

  res.status(201).json({
    id: result.insertId,
    credentials: {
      owner_name: name,
      username: email,
      temporary_password: tempPassword,
      staff_id_code: staffIdCode
    }
  });
};

export const updateStaff = async (req, res) => {
  const db = getDb();
  const { id } = req.params;
  const { name, email, role } = req.body;
  const notaryId = req.user.notary_id;

  await db.execute(
    "UPDATE users SET name = ?, email = ?, role = ? WHERE id = ? AND notary_id = ?",
    [name, email, role, id, notaryId]
  );

  await logAction(req.user.id, "UPDATE_STAFF", `Updated staff member: ${name} (ID: ${id})`);

  res.json({ message: "Staff updated" });
};

export const deleteStaff = async (req, res) => {
  const db = getDb();
  const { id } = req.params;
  const notaryId = req.user.notary_id;

  await db.execute("DELETE FROM users WHERE id = ? AND notary_id = ?", [id, notaryId]);

  await logAction(req.user.id, "DELETE_STAFF", `Deleted staff member ID: ${id}`);
  res.json({ message: "Staff deleted" });
};

export const resetStaffPassword = async (req, res) => {
  const db = getDb();
  const { id } = req.params;
  const notaryId = req.user.notary_id;

  const [rows] = await db.execute("SELECT name, email FROM users WHERE id = ? AND notary_id = ?", [id, notaryId]);
  const user = rows[0];

  if (!user) {
    return res.status(404).json({ message: "Staff not found" });
  }

  const tempPassword = Math.random().toString(36).slice(-8);
  const passwordHash = await bcrypt.hash(tempPassword, 10);

  await db.execute(
    "UPDATE users SET password_hash = ?, password_must_change = 1 WHERE id = ? AND notary_id = ?",
    [passwordHash, id, notaryId]
  );

  await logAction(req.user.id, "RESET_STAFF_PASSWORD", `Reset password for staff member: ${user.name} (ID: ${id})`);

  res.json({
    message: "Password reset successfully",
    credentials: {
      owner_name: user.name,
      username: user.email,
      temporary_password: tempPassword
    }
  });
};
