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

export const listNotaries = async (_req, res) => {
  const db = getDb();
  const [rows] = await db.execute(`
    SELECT n.id, n.name, n.region, n.district, n.category, n.registration_type, n.status, n.created_at, n.issued_date, n.expired_date,
           u.name AS owner_name, u.email AS owner_email,
           (SELECT applicant_phone FROM notary_applications na WHERE na.applicant_email = u.email ORDER BY created_at DESC LIMIT 1) AS owner_phone
    FROM notaries n
    LEFT JOIN users u ON n.owner_user_id = u.id
    ORDER BY n.name ASC
  `);
  res.json(rows);
};

export const renewNotary = async (req, res) => {
  const db = getDb();
  const { id } = req.params;
  const { issued_date, expired_date } = req.body;

  if (!issued_date || !expired_date) {
     return res.status(400).json({ message: "issued_date and expired_date are required" });
  }

  await db.execute(
    "UPDATE notaries SET issued_date = ?, expired_date = ?, registration_type = 'renewed' WHERE id = ?",
    [issued_date, expired_date, id]
  );

  await logAction(req.user.id, "RENEW_LICENSE", `Renewed license for notary ID: ${id}. New expiry: ${expired_date}`);

  res.json({ message: "Notary renewed successfully", issued_date, expired_date });
};

export const updateNotary = async (req, res) => {
  const db = getDb();
  const { id } = req.params;
  const { name, region, district, category, status } = req.body;

  if (!name || !region || !district || !category || !status) {
     return res.status(400).json({ message: "All fields are required" });
  }

  await db.execute(
    "UPDATE notaries SET name = ?, region = ?, district = ?, category = ?, status = ? WHERE id = ?",
    [name, region, district, category, status, id]
  );

  await logAction(req.user.id, "UPDATE_NOTARY", `Updated details for notary: ${name} (ID: ${id})`);


  res.json({ message: "Notary updated successfully", id, name, region, district, category, status });
};

export const resetNotaryPassword = async (req, res) => {
  const db = getDb();
  const { id } = req.params;

  const [notaryRows] = await db.execute("SELECT owner_user_id FROM notaries WHERE id = ?", [id]);
  const notary = notaryRows[0];

  if (!notary || !notary.owner_user_id) {
    return res.status(404).json({ message: "Notary or owner not found" });
  }

  const [userRows] = await db.execute("SELECT name, email FROM users WHERE id = ?", [notary.owner_user_id]);
  const user = userRows[0];

  if (!user) {
    return res.status(404).json({ message: "Owner user 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 = ?",
    [passwordHash, notary.owner_user_id]
  );

  await logAction(req.user.id, "RESET_NOTARY_PASSWORD", `Reset password for notary owner: ${user.name} (ID: ${notary.owner_user_id})`);

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