const pool = require("../config");

const getAllShiftDb = async (searchParams = {}) => {
  let queryParams = [];

  // Handle pagination
  if (searchParams.limit) {
    const page = Number(searchParams.page ?? 1) - 1;
    queryParams = [Number(searchParams.limit ?? 10), page];
  }

  const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
    ["a.shift_name", "a.start_time", "a.end_time"],
    searchParams.criteria,
    queryParams
  );
  if (whereParamOr) queryParams = whereParamOr;

  const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
    [
      { column: "a.shift_name", param: searchParams.name, type: "string" },
      { column: "a.start_time", param: searchParams.start_time, type: "time" },
      { column: "a.end_time", param: searchParams.end_time, type: "time" },
      { column: "a.is_active", param: searchParams.status, type: "string" },
    ],
    queryParams
  );
  if (whereParamAnd) queryParams = whereParamAnd;

  const queryText = `
    SELECT 
      COUNT(*) OVER() AS total_data, 
      a.*
    FROM m_shift a
    WHERE a.deleted_at IS NULL
      ${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
      ${whereOrConditions ? ` ${whereOrConditions}` : ""}
    ORDER BY a.shift_id ASC
     ${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ''}
  `;

  const result = await pool.query(queryText, queryParams);
  const total =
    result?.recordset?.length > 0
      ? parseInt(result.recordset[0].total_data, 10)
      : 0;

  return { data: result.recordset, total };
};

const getShiftByIdDb = async (id) => {
  const queryText = `
    SELECT 
      a.*
    FROM m_shift a
    WHERE a.shift_id = $1 AND a.deleted_at IS NULL
  `;
  const result = await pool.query(queryText, [id]);
  return result.recordset?.[0] || null;
};

const insertShiftDb = async (store) => {
  const { query: queryText, values } = pool.buildDynamicInsert("m_shift", store);
  const result = await pool.query(queryText, values);
  const insertedId = result.recordset?.[0]?.inserted_id;

  return insertedId ? await getShiftByIdDb(insertedId) : null;
};

const updateShiftDb = async (id, data) => {
  const store = { ...data };
  const whereData = { shift_id: id };

  const { query: queryText, values } = pool.buildDynamicUpdate(
    "m_shift",
    store,
    whereData
  );

  await pool.query(`${queryText} AND deleted_at IS NULL`, values);
  return getShiftByIdDb(id);
};

const deleteShiftDb = async (id, deletedBy) => {
  const queryText = `
    UPDATE m_shift
    SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
    WHERE shift_id = $2 AND deleted_at IS NULL
  `;
  await pool.query(queryText, [deletedBy, id]);
  return true;
};

module.exports = {
  getAllShiftDb,
  getShiftByIdDb,
  insertShiftDb,
  updateShiftDb,
  deleteShiftDb,
};
