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

const forgotPassword = async (req, res) => {
  const sqlStaff = `SELECT firstName, lastName, email FROM staffs WHERE email=?`;
  const sqlHospMan = `SELECT firstName, lastName, email FROM hospital_man WHERE email=?`;
  const updateStaff = `UPDATE staffs SET rcode=?, rcode_expires=DATE_ADD(NOW(), INTERVAL 10 MINUTE) WHERE email=?`;
  const updateHospMan = `UPDATE hospital_man SET rcode=?, rcode_expires=DATE_ADD(NOW(), INTERVAL 10 MINUTE) WHERE email=?`;

  const { email } = req.body;
  if (!email) throw "Email is required";

  let getUser = null;
  let updateSql = null;

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

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

  // Generate reset code and store expiration time (10 minutes)
  const reset_code = Math.floor(647523 + Math.random() * 90000);
  await db.execute(updateSql, [reset_code, getUser.email]);
  const year = new Date().getFullYear();
  const firstName = getUser.firstName;
  const lastName = getUser.lastName;
  // Send the email with the reset code
  const subject = "Password Reset Code";
  const message = `
  <!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Password Reset Code</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;
        }
        .code {
            font-size: 24px;
            font-weight: bold;
            color: #d9534f;
            text-align: center;
            margin: 20px 0;
            padding: 10px;
            background: #f8d7da;
            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 Request</div>
        <div class="content">
            <p>Hi <strong>${firstName} ${lastName}</strong>,</p>
            <p>You recently requested to reset your password. Please use the code below to reset it:</p>
            <div class="code">${reset_code}</div>
            <p>This code will expire in <strong>10 minutes</strong>. If you did not request this, please ignore this email and notify the administrative office immediatley.</p>
        </div>
        <div class="footer">
            &copy; ${year} ${process.env.hosp_name}. All rights reserved.
        </div>
    </div>
</body>
</html>
`;

  await sendEmail(email, subject, message);

  res.status(200).json({
    status: "Success",
    message: `Reset code sent successfully to ${email}. It will expire in 10 minutes.`,
  });
};

module.exports = forgotPassword;
