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

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

  let data;
  const seleectVitalsSql = `SELECT * FROM vitals ORDER BY date_time DESC LIMIT ? OFFSET ?`;
  const selectWhereSql = `SELECT * FROM vitals WHERE pt_id=?`;
  const checkPtSql = `SELECT patient_id FROM patients WHERE patient_id=? OR phone_num=?`;

  if (id) {
    const [pt] = await db.execute(checkPtSql, [id, id]);
    if (pt.length < 1) throw "Patient NOT found! Incorrect ID";

    const [pt_vt] = await db.execute(selectWhereSql, [pt[0].patient_id]);
    if (pt_vt.length < 1) throw "No vital signs record found for this patient.";
    data = pt_vt;
    //console.log(data);
  } else {
    [data] = await db.execute(seleectVitalsSql, [limit, offset]);
  }

  const c_data = transformDateTimeField(data);
  const v_data = cleanVitalsData(c_data);

  res.status(200).json({
    status: "success",
    vitals: v_data,
    page,
  });
};

module.exports = getVitals;
