//const logger = require("../../../handlers/logger");
const db = require("../../../managers/dbConfig");
const safeAxios = require("../../../managers/safeAxios");
const validator = require("validator");
const sendEmail = require("../../../managers/mailManager");
const {
  generateSystemFingerprint,
} = require("../../../managers/systemFingerprint");
const ONLINE_REG_URL = process.env.ONLINE_REG_URL;

const registerHosp = async (req, res, next) => {
  const { name, code_name, address, email, phone_num, slogan } = req.body;

  if (!name || !address || !email || !phone_num || !code_name)
    return next("All required fields must be provided.");

  const machineId = generateSystemFingerprint();

  const [err, onlineData] = await safeAxios.post(ONLINE_REG_URL, {
    name,
    code_name,
    address,
    email,
    phone_num,
    slogan,
    machine_id: machineId,
  });
  // console.log(err);

  if (err) throw `${err.message}`; // auto handled by error middleware

  // proceed to save onlineData...
  const connection = db.getConnection();
  if (!connection) throw "Database connection failed";
  await connection.beginTransaction();

  const insertSql = `
    INSERT INTO hospitals (name, code_name, address, phone_num, email, slogan, online_id, branch_id, machine_id)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`;
  await connection.execute(insertSql, [
    onlineData.name,
    onlineData.code_name,
    onlineData.address,
    onlineData.phone_num,
    onlineData.email,
    onlineData.slogan,
    onlineData.online_id,
    onlineData.online_id,
    machineId,
  ]);

  const updateHospitalManTableSql = `
    UPDATE hospital_man SET branch_id = ? WHERE machine_id = ?`;

  await connection.execute(updateHospitalManTableSql, [
    onlineData.online_id,
    machineId,
  ]);

  await connection.commitTransaction();
  await connection.release();

  res.status(201).json({ status: "success" });
};

const registerHospitalOnline = async (req, res) => {
  const { name, code_name, address, email, phone_num, slogan, machine_id } =
    req.body;

  if (!name || !address || !email || !phone_num || !code_name)
    throw "All required fields must be provided.";
  if (!validator.isEmail(email)) throw "Invalid email format";

  const checkSql = "SELECT * FROM hospitals WHERE email=? OR phone_num=?";
  const [existing] = await db.execute(checkSql, [email, phone_num]);
  if (existing.length > 0) {
    throw "A hospital with that email or phone already exists online.";
  }

  const insertSql = `
    INSERT INTO hospitals (name, code_name, address, phone_num, machine_id, email, slogan)
    VALUES (?, ?, ?, ?, ?, ?, ?)`;
  const [result] = await db.execute(insertSql, [
    name,
    code_name,
    address,
    phone_num,
    machine_id,
    email,
    slogan,
  ]);

  const online_id = result.insertId;

  res.status(201).json({
    name,
    code_name,
    address,
    phone_num,
    email,
    slogan,
    online_id,
  });

  const subject = "Welcome Onboard";
  const msg = `<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome to G.O-EMR</title>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
        .container { max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #ddd; border-radius: 5px; background-color: #f9f9f9; }
        .btn { display: inline-block; padding: 10px 15px; margin-top: 10px; color: #fff; background-color: #007bff; text-decoration: none; border-radius: 5px; }
        .btn:hover { background-color: #0056b3; }
    </style>
</head>
<body>
    <div class="container">
        <h2>Welcome to G.O-EMR!</h2>
        <p>Dear <strong>Admin Officer</strong>,</p>
        <p>We’re excited to have <strong>${name}</strong> on board! Our hospital management software is designed to streamline operations, enhance efficiency, and improve patient care.</p>
        
        <h3>Next Steps:</h3>
        <ul>
            <li><strong>Log in to Your Admin Dashboard:</strong> <a href="[Login URL]" class="btn">Access Your Dashboard With Your SECRET KEYS</a></li>
            <li><strong>Register Your Hospital Staff:</strong> As the admin, you are responsible for creating accounts for doctors, nurses, and other staff members.</li>
            <li><strong>Explore the Features:</strong> Manage patients, appointments, billing, and more from one easy-to-use platform.</li>
        </ul>

        <p>If you need any assistance, our support team is available at <a href="mailto:support@1link.com.ng">support@1link.com.ng</a> or <strong>08133667861</strong>.</p>

        <p>We look forward to supporting your hospital’s success!</p>

        <p>Best regards,</p>
        <p><strong>Abdullahi Olaniyan</strong><br>
        <strong>Chief Technical Officer</strong><br>
        <strong>G.O-Developers Group</strong><br>
        <a href="https://wa.me/2348133667861">Click here to contact Us On whatsApp</a></p>
    </div>
</body>
</html>
`;

  // await sendEmail(email, subject, msg);
};

module.exports = { registerHospitalOnline, registerHosp };
