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

const registerHmoAndGroup = async (req, res) => {
  let {
    type,
    name,
    code_name,
    address,
    contact_person,
    contact_email,
    contact_num,
  } = req.body;
  if (!type) throw "Type (HMO, Family, or Other Group) is required.";
  if (type !== "HMO" && type !== "Family" && type !== "Other Group")
    throw "Type must be either 'HMO', 'Family', or 'Other Group'.";
  if (!name) throw "Name is required.";

  // if (!contact_email) throw "Contact email is required.";
  if (!contact_num) throw "Contact number is required.";

  // ✅ SQL Queries (on separate lines)
  const checkExistingFamilyOrHmoSQL = `
        SELECT name,contact_email,phone_num
        FROM families 
        WHERE contact_email = ? OR name=?`;

  const insertFamilyOrGroupSql = `
        INSERT INTO families (name, address, contact_person, contact_email, phone_num, type) 
        VALUES (?, ?, ?, ?, ?, ?)`;

  const checkHmosSql = `
        SELECT code_name,contact_email,phone_num
        FROM hmo_reg 
        WHERE contact_email = ? OR code_name=?`;

  const insertHmoSql = `
        INSERT INTO hmo_reg (name,code_name, address, contact_person, contact_email, phone_num) 
        VALUES (?, ?, ?, ?, ?, ?)`;

  if (type === "HMO") {
    if (!code_name) throw "HMO Code-Name is required.e.g. NHIS";
    // Ensure email is unique
    const [existingHmo] = await db.execute(checkHmosSql, [
      contact_email,
      code_name,
    ]);
    if (existingHmo[0] !== undefined) {
      if (existingHmo[0].contact_email === contact_email)
        throw `An HMO with email ${contact_email} already exists`;
      if (existingHmo[0].code_name === code_name)
        throw `An HMO with code-name ${code_name} already exists`;
      if (existingHmo[0].phone_num === phone_num)
        throw `An HMO with contact number ${phone_num} already exists`;
    }

    // ✅ Insert into database
    await db.execute(insertHmoSql, [
      name || null,
      code_name || null,
      address || null,
      contact_person || null,
      contact_email || "N/A",
      contact_num || "N/A",
    ]);
  } else if (type === "Family" || type === "Other Group") {
    // ✅ Ensure email is unique
    const [existingFamily] = await db.execute(checkExistingFamilyOrHmoSQL, [
      contact_email,
      name,
    ]);
    if (existingFamily[0] !== undefined) {
      if (existingFamily[0].contact_email === contact_email)
        throw `A family or Group with email ${contact_email} already exists`;
      if (existingFamily[0].name === name)
        throw `A family or Group with name ${name} already exists`;
      if (existingFamily[0].phone_num === contact_num)
        throw `A family or Group with contact number ${contact_num} already exists`;
    }

    if (type === "Other Group") {
      type = "Group";
    }

    // ✅ Insert into database
    await db.execute(insertFamilyOrGroupSql, [
      name || null,
      address || null,
      contact_person || null,
      contact_email || "N/A",
      contact_num || "N/A",
      type,
    ]);
  }

  res.status(201).json({
    status: "Success",
    message: "Registration successful.",
  });
};

// updating an existing HMO record.

const updateHmo = async (req, res) => {
  const {
    id,
    name,
    code_name,
    address,
    contact_person,
    contact_email,
    contact_num,
  } = req.body;

  // ✅ Check required field (ID is necessary to update a record)
  if (!id) throw "HMO ID is required for updating.";

  // ✅ SQL Queries (on separate lines)
  const checkHmoSql = `
        SELECT * 
        FROM hmo_reg 
        WHERE id = ?`;

  const updateHmoSql = `
        UPDATE hmo_reg 
        SET name = ?,
            code_name = ?,
            address = ?, 
            contact_person = ?, 
            contact_email = ?, 
            phone_num = ? 
        WHERE id = ?`;

  // ✅ Check if the HMO exists
  const [existingHmo] = await db.execute(checkHmoSql, [id]);
  if (existingHmo.length === 0) throw `No HMO found with ID ${id}.`;

  // ✅ Update the HMO record
  await db.execute(updateHmoSql, [
    name || existingHmo[0].name,
    code_name || existingHmo[0].code_name,
    address || existingHmo[0].address,
    contact_person || existingHmo[0].contact_person,
    contact_email || existingHmo[0].contact_email,
    contact_num || existingHmo[0].phone_num,
    id,
  ]);

  res.status(200).json({
    status: "Success",
    message: `HMO record with ID ${id} updated successfully.`,
  });
};

module.exports = { registerHmoAndGroup, updateHmo };
