const bcryptjs = require("bcryptjs");
const sendEmail = require("../../managers/mailManager");
const db = require("../../managers/dbConfig");

const offlinePasswordReset = async (req, res, next) => {
  const salt = await bcryptjs.genSalt(10);
  const { email, sPIN, new_password, confirm_password } = req.body;

  if (!email || !sPIN || !new_password || !confirm_password) {
    return res.status(400).json({
      status: "failed",
      error: "Email, sPIN, new password, and confirmation are all required",
    });
  }

  if (new_password !== confirm_password) {
    return res.status(400).json({
      status: "failed",
      error: "New password and confirm password do not match",
    });
  }

  const sql = `SELECT id, sPIN FROM staffs WHERE email = ? LIMIT 1`;

  try {
    const [rows] = await db.execute(sql, [email]);

    if (rows.length === 0) {
      return res.status(404).json({
        status: "failed",
        error: "Staff with email " + email + " not found",
      });
    }

    const staff = rows[0];

    if (staff.sPIN === null || staff.sPIN === undefined) {
      return res.status(400).json({
        status: "failed",
        error: "Staff does not have a secret PIN set",
      });
    }
    const validPIN = await bcryptjs.compare(sPIN, staff.sPIN);

    if (validPIN === false) {
      return res
        .status(401)
        .json({ status: "failed", error: "Invalid secret PIN" });
    }

    const hashedPassword = await bcryptjs.hash(new_password, salt);

    await db.execute(`UPDATE staffs SET password = ? WHERE id = ?`, [
      hashedPassword,
      staff.id,
    ]);

    res.status(200).json({
      status: "success",
      message: "Password updated successfully",
    });
  } catch (err) {
    next(err);
  }
};

const resetPassword = async (req, res) => {
  const sqlStaff = `SELECT firstName, lastName, rcode, rcode_expires, email FROM staffs WHERE email=?`;
  const sqlHospMan = `SELECT firstName, lastName, rcode, rcode_expires, email FROM hospital_man WHERE email=?`;
  const updateStaff = `UPDATE staffs SET password=?, rcode=NULL, rcode_expires=NULL WHERE email=?`;
  const updateHospMan = `UPDATE hospital_man SET password=?, rcode=NULL, rcode_expires=NULL WHERE email=?`;

  const { email, reset_code, password, confirmPassword } = req.body;
  // console.log(typeof reset_code);

  if (!email) throw "Email is required";
  if (!reset_code) throw "Reset Code must be provided!";
  if (!password) throw "Please provide a new password";
  if (!confirmPassword || password !== confirmPassword)
    throw "Password and confirm password do not match";

  let getUserAndCode = null;
  let updateSql = null;

  // Check if the email exists in "staffs"
  const [staffResult] = await db.execute(sqlStaff, [email]);
  if (staffResult.length > 0) {
    getUserAndCode = staffResult[0];
    updateSql = updateStaff;
  } else {
    // Check if the email exists in "hospital_man"
    const [hospManResult] = await db.execute(sqlHospMan, [email]);
    if (hospManResult.length > 0) {
      getUserAndCode = hospManResult[0];
      updateSql = updateHospMan;
    }
  }

  // If user does not exist in both tables
  if (!getUserAndCode)
    throw `User with email ${email} does not exist at ${process.env.hosp_name}.`;

  // Check if reset code exists and is not expired
  if (reset_code === null || getUserAndCode.rcode != reset_code)
    throw "Invalid or incorrect reset code.";

  if (new Date(getUserAndCode.rcode_expires) < new Date())
    throw "Reset code has expired. Please request a new one.";

  // Hash the new password
  const salt = await bcryptjs.genSalt();
  const hashedPassword = await bcryptjs.hash(password, salt);

  // Update password and clear reset code
  await db.execute(updateSql, [hashedPassword, email]);

  const firstName = getUserAndCode.firstName;
  const lastName = getUserAndCode.lastName;

  // Send email notification
  const subject = "Password Reset Successfully";
  const message = `
  <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>Password Reset Confirmation</title>
            <style>
                body { font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px; }
                 .container {
            max-width: 500px;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            margin: 20px auto; /* Reducing top margin to fix extra space */
        }
                .header { text-align: center; font-size: 20px; font-weight: bold; color: #333; }
                .content { margin-top: 15px; font-size: 16px; color: #555; }
                .message { font-size: 18px; color: #28a745; text-align: center;
                           margin: 20px 0; padding: 10px; background: #d4edda; border-radius: 5px; }
                .footer { margin-top: 20px; font-size: 14px; color: #777; text-align: center; }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">Password Reset Successful</div>
                <div class="content">
                    <p>Hi <strong>${firstName} ${lastName}</strong>,</p>
                    <p>Your password has been successfully reset.</p>
                    <div class="message">You can now log in with your new password.</div>
                    <p>If you did not request this change, please contact your admin or technical officer immediately.</p>
                </div>
                <div class="footer">
                    &copy; ${new Date().getFullYear()} ${
    process.env.hosp_name
  }. All rights reserved.
                </div>
            </div>
        </body>
        </html>`;

  // await sendEmail(email, subject, message);

  res.status(200).json({
    status: "Success",
    message: "Password reset successfully.",
  });
};

module.exports = { resetPassword, offlinePasswordReset };
