const validator = require("validator");
const db = require("../../../../managers/dbConfig");

const recordVitals = async (req, res) => {
  const pageUser = req.user.cadre;
  if (
    pageUser !== "Doctor" &&
    pageUser !== "Nurse" &&
    pageUser !== "CHP" &&
    pageUser !== "CHO"
  )
    throw "You're NOT Permitted To Use This Resources";
  let { pt_id, age, sys, dia, pr, temp, rr, weight, height } = req.body;
  const sentId = req.query;

  const insertToVitalsSql = `INSERT INTO vitals(
    pt_id,
    temp,
    pulse_rate,
    resp_rate,
    systolic,
    diastolic,
    Weight,
    height,
    age,
    gender,
    bmi
  ) VALUES(?,?,?,?,?,?,?,?,?,?,?)`;

  const selectFromPatientsSql = `SELECT patient_id, gender, age FROM patients WHERE phone_num=? OR patient_id=?`;

  if (!pt_id) throw "Patient ID OR Phone Number is required!";

  if (!validator.isNumeric(sys.toString()) && sys !== "")
    throw "Systolic Pressure can only be Numbers!";
  if (!validator.isNumeric(dia.toString()) && dia !== "")
    throw "Diastolic Pressure can only be Numbers!";
  if (!validator.isNumeric(pr.toString()) && pr !== "")
    throw "Pulse can only be Numbers!";
  if (!validator.isNumeric(temp.toString()) && temp !== "")
    throw "Temperature Level can only be Numbers!";
  if (!validator.isNumeric(rr.toString()) && rr !== "")
    throw "Respiratory Rate can only be Numbers!";
  if (!validator.isNumeric(weight.toString()) && weight !== "")
    throw "Weight can only be Numbers!";
  if (!validator.isNumeric(height.toString()) && height !== "")
    throw "Height can only be Numbers!";
  if (age && !validator.isNumeric(age.toString()))
    throw "Age can only be Numbers!";

  const [getPT] = await db.execute(selectFromPatientsSql, [pt_id, pt_id]);

  if (getPT.length === 0) throw "INCORRECT patient ID or Phone Number";
  const id = getPT[0]["patient_id"];
  const gender = getPT[0]["gender"];
  const patientAge = age ? age : getPT[0]["age"];

  // Replace empty strings with null before database insertion
  sys = sys === "" ? null : sys;
  dia = dia === "" ? null : dia;
  pr = pr === "" ? null : pr;
  temp = temp === "" ? null : temp;
  rr = rr === "" ? null : rr;
  weight = weight === "" ? null : weight;
  height = height === "" ? null : height;

  let bmi = null;
  if (weight && height) {
    const heightInMeters = height / 100;
    bmi = weight / (heightInMeters * heightInMeters);
  }

  await db.execute(insertToVitalsSql, [
    id,
    temp,
    pr,
    rr,
    sys,
    dia,
    weight,
    height,
    patientAge,
    gender,
    bmi,
  ]);

  res.status(201).json({
    status: "success",
    message: "Record saved Successfully",
  });
};

module.exports = recordVitals;
