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

const getPatient = async (req, res) => {
  const today = getFormattedDateTime();
  const {sentId} = req.query;
  if (!sentId) throw "Please provide valid patient ID or phone number";
  const sql =
    "SELECT title,firstName,lastName,age,phone_num,patient_id FROM patients WHERE patient_id=? OR phone_num=?";
  // const sql1 =
  //   "SELECT COUNT(*) FROM patients WHERE phone_num=? OR patient_id=?";
  const sql1 = `SELECT patient_id, phone_num FROM patients WHERE phone_num=? OR patient_id=?`;
  const sql2 = `
    SELECT
        p.patient_id, 
        p.title,
        p.firstName, 
        p.lastName, 
        p.age, 
        p.phone_num, 
        v.temp, 
        v.pulse_rate, 
        v.systolic, 
        v.diastolic, 
        v.weight,
        v.height,
        v.date_time
    FROM patients p
    LEFT JOIN (
        SELECT * 
        FROM vitals 
        WHERE DATE(date_time) = ?
        ORDER BY date_time DESC
        LIMIT 1
    ) AS v ON p.patient_id = v.pt_id
    WHERE p.patient_id = ?`;

  const [getPT] = await db.execute(sql1, [sentId, sentId]);
  if (getPT.length === 0) throw "INCORRECT patient ID or Phone Number";
  const id = getPT[0]["patient_id"];

  const row = await db.execute(sql2, [today, id]);
  const patientData = row[0][0];
  const temp = patientData.temp == 0.0 ? null : patientData.temp;
  const weight = patientData.weight == 0 ? null : patientData.weight;
  const height = patientData.height == 0 ? null : patientData.height;
  const systolic = patientData.systolic == 0.0 ? null : patientData.systolic;
  const diastolic = patientData.diastolic == 0 ? null : patientData.diastolic;
  const pulse_rate =
    patientData.pulse_rate == 0 ? null : patientData.pulse_rate;

  patientData.temp = temp;
  patientData.weight = weight;
  patientData.height = height;
  patientData.systolic = systolic;
  patientData.diastolic = diastolic;
  patientData.pulse_rate = pulse_rate;

  // console.log(rTemp);
  //console.log(patientData);
  res.status(200).json({
    status: "success",
    ...patientData,
  });
};

const getPtBioData = async (req, res) => {
  const id = req.params.id;
  if (!id) throw "Please provide valid patient ID or phone number";

  const sql = `SELECT * FROM patients WHERE patient_id=?`;
  const sql1 = `SELECT patient_id, phone_num FROM patients WHERE phone_num=? OR patient_id=?`;
  const [getPT] = await db.execute(sql1, [id, id]);

  if (getPT.length === 0) throw "INCORRECT patient ID or Phone Number";
  const pt_id = getPT[0]["patient_id"];

  const [data] = await db.execute(sql, [pt_id]);

  res.status(200).json({
    status: "success",
    ...data[0],
  });
};
module.exports = { getPatient, getPtBioData };
