const dayjs = require("dayjs");
const utc = require("dayjs/plugin/utc");
const db = require("../../../managers/dbConfig");
const { transformDateTimeField } = require("../../../managers/formatDateTime");
const { attachCalculatedAges } = require("../../../managers/customFormaters");

//* Retrieves patient bio data based on various filters
/**
 * Retrieves patient bio data based on various filters.
 * Supports pagination and searching by patient ID, phone number, or names.
 *
 * @param {Object} req - The request object containing pagination and search parameters.
 * @param {Object} res - The response object to send the results.
 */

const getBioData = async (req, res) => {
  let { page, limit, offset, search_type, q } = req.pagination;

  //console.log("BioData Pagination:", req.pagination);

  const fallbackSql = `SELECT * FROM patients ORDER BY date_time DESC LIMIT ? OFFSET ?`;
  let getPatientDetails;

  if (!search_type || !q || q.trim() === "") {
    // Return paginated default data if no search
    [getPatientDetails] = await db.execute(fallbackSql, [limit, offset]);
  } else {
    // Search logic
    const qValue = `%${q.trim()}%`;

    switch (search_type) {
      case "default":
        [getPatientDetails] = await db.execute(fallbackSql, [limit, offset]);
        break;
      case "patient_id":
        const sqlByID = `SELECT * FROM patients WHERE patient_id LIKE ? ORDER BY date_time DESC LIMIT ? OFFSET ?`;
        [getPatientDetails] = await db.execute(sqlByID, [
          qValue,
          limit,
          offset,
        ]);
        break;

      case "patient_phone_number":
        const sqlByPhone = `SELECT * FROM patients WHERE phone_num LIKE ? ORDER BY date_time DESC LIMIT ? OFFSET ?`;
        [getPatientDetails] = await db.execute(sqlByPhone, [
          qValue,
          limit,
          offset,
        ]);
        break;

      case "hmo_code_name":
        const sqlByHMO = `
          SELECT * FROM patients 
          WHERE hmo LIKE ? 
          ORDER BY date_time DESC 
          LIMIT ? OFFSET ?
        `;
        [getPatientDetails] = await db.execute(sqlByHMO, [
          qValue,
          limit,
          offset,
        ]);
        break;

      case "family/group_name":
        const sqlByFamily = `
          SELECT * FROM patients 
          WHERE family_or_group LIKE ? 
          ORDER BY date_time DESC 
          LIMIT ? OFFSET ?
        `;
        [getPatientDetails] = await db.execute(sqlByFamily, [
          qValue,
          limit,
          offset,
        ]);
        break;
      case "firstName":
        const sqlByFName = `SELECT * FROM patients WHERE firstName LIKE ? ORDER BY date_time DESC LIMIT ? OFFSET ?`;
        [getPatientDetails] = await db.execute(sqlByFName, [
          qValue,
          limit,
          offset,
        ]);
        break;

      case "lastName(surname)":
        const sqlByLName = `SELECT * FROM patients WHERE lastName LIKE ? ORDER BY date_time DESC LIMIT ? OFFSET ?`;
        [getPatientDetails] = await db.execute(sqlByLName, [
          qValue,
          limit,
          offset,
        ]);
        break;

      default:
        throw `Unsupported search type: ${search_type}`;
    }
  }

  let patientDetails = transformDateTimeField(getPatientDetails);
  patientDetails = attachCalculatedAges(patientDetails);
  // console.log(patientDetails);

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

module.exports = { getBioData };
