const db = require("../../../managers/dbConfig");
const { transformDateTimeField } = require("../../../managers/formatDateTime");

// Function to fetch HMOs (with optional filtering)
const filterHMOs = async (req, res) => {
  const { name } = req.query; // Get 'name' filter from client if provided

  let sql = `SELECT * FROM hmo_reg`;

  const values = [];

  if (name) {
    sql += ` WHERE code_name LIKE ?`; // Allow filtering by HMO name
    values.push(`%${name}%`);
  }

  //sql += ` ORDER BY name ASC`; // Always sort alphabetically

  let [rows] = await db.execute(sql, values);

  if (rows.length === 0) throw "No HMOs found";

  rows = transformDateTimeField(rows);

  res.status(200).json({ status: "success", data: rows });
};

const hmoCounter = async (req, res) => {
  const countSql = `SELECT COUNT(*) FROM hmo_reg`;
  const [hmoCount] = await db.execute(countSql);
  const total_hmo = hmoCount[0]["COUNT(*)"];
  //console.log(total_hmo);
  res.status(200).json({
    status: "success",
    message: "counted successfully",
    total_hmo,
  });
};

module.exports = { filterHMOs, hmoCounter };
