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

const rdashBoard = async (req, res) => {
  const userProfile = req.user;
//   if (
//     userProfile.cadre !== "MRO" &&
//     userProfile.cadre !== "Medical Record Officer" &&
//     userProfile.rank !== 1
//   )
//     throw "You're not permitted to Access this Resources";

  const currentYearMonth = getCurrentYearMonth();
  const year = new Date().getFullYear();
  const startDate = `${year}-01`;
  const endDate = `${year}-12`;
  let monthlyRegCount;

  const date = getFormattedDateTime();

  const sql = `SELECT * FROM patients ORDER BY id DESC LIMIT 10`;

  const sql1 = `SELECT total_count
  FROM counters
  WHERE table_name = ? AND month_year = ?`;

  const sql2 = `SELECT COUNT(*) FROM patients WHERE DATE(date_time)=?`;

  const sql3 = `SELECT SUM(total_count) AS total_pt
  FROM counters
  WHERE table_name = ?
  AND month_year BETWEEN ? AND ?`;

  const [regCountToday] = await db.execute(sql2, [date]);
  const todayRegCount = regCountToday[0]["COUNT(*)"];

  const [reg_count] = await db.execute(sql1, ["patients", currentYearMonth]);
  if (reg_count[0]) {
    monthlyRegCount = reg_count[0].total_count;
  }

  const [y_count] = await db.execute(sql3, ["patients", startDate, endDate]);
  const yearlyRegCount = y_count[0].total_pt;

  const [getPatientDetails] = await db.execute(sql);
  const patientDetails = transformDateTimeField(getPatientDetails);
  //console.log(patientDetails);

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

module.exports = rdashBoard;
