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

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

  const sql1 = `SELECT staff_id, phone_num FROM staffs WHERE staff_id=? OR phone_num=?`;
  const sql = `SELECT staff_id, firstName, lastName, email, phone_num,cadre FROM staffs ORDER BY id DESC LIMIT ? OFFSET ?`;
  let getStaffDetails;

  if (id) {
    const _sql = `SELECT staff_id, firstName, lastName, email, phone_num,cadre FROM staffs WHERE staff_id=?`;
    const [validID] = await db.execute(sql1, [id, id]);

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

    [getStaffDetails] = await db.execute(_sql, [id]);
  } else {
    [getStaffDetails] = await db.execute(sql, [limit, offset]);
  }

  const staffDetails = transformDateTimeField(getStaffDetails);
  //console.log(staffDetails);

  res.status(200).json({
    status: "success",
    page,
    data: staffDetails,
  });
};

module.exports = getStaff;
