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

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

  const sql1 = `SELECT patient_id, phone_num FROM patients WHERE patient_id=? OR phone_num=? OR firstName LIKE ? OR lastName LIKE ?`;
  const sql = `SELECT * FROM patients ORDER BY date_time DESC LIMIT ? OFFSET ?`;
  let getPatientDetails;

  if (id) {
    const _sql = `SELECT * FROM patients WHERE patient_id=?`;
    const [validID] = await db.execute(sql1, [id, id, `%${id}%`, `%${id}%`]);

    if (validID.length === 0) throw "INCORRECT Patient ID or Phone Number";
    id = validID[0]["patient_id"];

    [getPatientDetails] = await db.execute(_sql, [id]);
  } else {
    [getPatientDetails] = await db.execute(sql, [limit, offset]);
  }

  const patientDetails = transformDateTimeField(getPatientDetails);
  //console.log(patientDetails);

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

module.exports = { getBioData };
