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

const logger = require("../../../../handlers/logger");

const getRxHx = async (req, res) => {
  let { id, limit, offset, page, start_date, end_date } = req.pagination;
  let rxData;

  const sql1 = `SELECT patient_id, phone_num FROM patients WHERE patient_id=? OR phone_num=?`;

  if (id) {
    let sql = `SELECT tx.*, patients.firstName, patients.lastName, patients.gender, patients.age 
    FROM tx
    LEFT JOIN patients ON tx.patient_id = patients.patient_id
    WHERE tx.patient_id=?
    `;

    const [validID] = await db.execute(sql1, [id, id]);

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

    let sqlParams = [id];

    // Add Date Filtering
    if (start_date && end_date) {
      sql += ` AND DATE(tx.date_time) BETWEEN ? AND ? `;
      sqlParams.push(start_date, end_date);
    }

    sql += `ORDER BY tx.id DESC LIMIT ? OFFSET ?`;
    sqlParams.push(limit, offset);

    [rxData] = await db.execute(sql, sqlParams);
  } else {
    let sql = `SELECT tx.*, patients.firstName, patients.lastName, patients.gender, patients.age 
    FROM tx
    LEFT JOIN patients ON tx.patient_id = patients.patient_id
    `;

    let sqlParams = [];

    // Add Date Filtering
    if (start_date && end_date) {
      sql += ` WHERE DATE(tx.date_time) BETWEEN ? AND ? `;
      sqlParams.push(start_date, end_date);
    }

    sql += `ORDER BY tx.id DESC LIMIT ? OFFSET ?`;
    sqlParams.push(limit, offset);

    [rxData] = await db.execute(sql, sqlParams);
  }

  const sanitizedDateTime = transformDateTimeField(rxData);

  const encryptedData = [
    "c_o",
    "hx",
    "drug_hx",
    "o_e",
    "lab_inv",
    "diag",
    "rx",
    "dr_note",
  ];
  const decryptedData = decryptRecords(
    sanitizedDateTime,
    process.env.enc_key,
    encryptedData
  );
  // console.log(rxData);

  res.json({
    page,
    data: decryptedData,
  });
};

module.exports = { getRxHx };
