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

const getAllUserScheduleDb = 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.user_id", "a.user_schedule_id", "a.schedule_id", "a.user_schedule_id", "a.shift_id"],
    searchParams.criteria,
    queryParams
  );
  if (whereParamOr) queryParams = whereParamOr;

  const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
    [
      { column: "a.user_id", param: searchParams.user_id, type: "int" },
      {
        column: "a.user_schedule_id",
        param: searchParams.user_schedule_id,
        type: "int",
      },
      { column: "a.schedule_id", param: searchParams.schedule_id, type: "int" },
      { column: "a.shift_id", param: searchParams.shift_id, type: "int" },
    ],
    queryParams
  );
  if (whereParamAnd) queryParams = whereParamAnd;

  const queryText = `
    SELECT 
      COUNT(*) OVER() AS total_data,
      a.*, 
      c.shift_name,
      c.start_time,
      c.end_time,
      d.user_fullname,
      d.user_name,
      d.user_phone
    FROM user_schedule a
    LEFT JOIN schedule b ON a.schedule_id = b.schedule_id
    LEFT JOIN m_shift c ON a.shift_id = c.shift_id
    LEFT JOIN m_users d ON a.user_id = d.user_id
    WHERE a.deleted_at IS NULL
      ${
        whereConditions.length > 0
          ? ` AND ${whereConditions.join(" AND ")}`
          : ""
      }
      ${whereOrConditions ? ` ${whereOrConditions}` : ""}
    ORDER BY c.shift_id ASC
    ${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ""}
  `;

  const result = await pool.query(queryText, queryParams);
  const records = result.recordset || [];

  const total = records.length > 0 ? parseInt(records[0].total_data, 10) : 0;

  const groupedShift = {};
  records.forEach((row) => {
    if (!groupedShift[row.shift_id]) {
      groupedShift[row.shift_id] = {
        shift: {
          shift_id: row.shift_id,
          shift_name: row.shift_name,
          start_time: row.start_time,
          end_time: row.end_time,
          users: [],
        },
      };
    }

    groupedShift[row.shift_id].shift.users.push({
      user_schedule_id: row.user_schedule_id,
      user_id: row.user_id,
      user_fullname: row.user_fullname,
      user_name: row.user_name,
      user_phone: row.user_phone,
    });
  });

  const data = Object.values(groupedShift);

  return { data, total };
};

const getUserScheduleById = async (userId, shiftId) => {
  const queryText = `
    SELECT 
      a.user_schedule_id,
      a.user_id,
      a.shift_id
    FROM user_schedule a
    WHERE a.user_id = $1 
      AND a.shift_id = $2 
      AND a.deleted_at IS NULL
  `;
  const result = await pool.query(queryText, [userId, shiftId]);
  return result.recordset || [];
};

const getUserScheduleByIdDb = async (id) => {
  const queryText = `
     SELECT 
      a.*,
      b.schedule_date,
      c.shift_name,
      c.start_time,
      c.end_time,
      d.user_fullname,
      d.user_name,
      d.user_phone
    FROM user_schedule a
    LEFT JOIN schedule b ON a.schedule_id = b.schedule_id
    LEFT JOIN m_shift c ON a.shift_id = c.shift_id
    LEFT JOIN m_users d ON a.user_id = d.user_id 
    WHERE a.user_schedule_id = $1 AND a.deleted_at IS NULL
  `;
  const result = await pool.query(queryText, [id]);
  return result.recordset?.[0] || null;
};

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

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

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

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

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

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

module.exports = {
  getAllUserScheduleDb,
  getUserScheduleByIdDb,
  insertUserScheduleDb,
  updateUserScheduleDb,
  deleteUserScheduleDb,
  getUserScheduleById,
};
