const pool = require("../config");
const { formattedDate } = require("../utils/date");

const normalizeClause = (clause) => {
  if (!clause) return "";
  return clause.replace(/^\s*(?:AND|WHERE)\s*/i, "").trim();
};

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

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

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

  const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
    [
      {
        column: "a.schedule_date",
        param: searchParams.name,
        type: "date",
      },
    ],
    queryParams
  );
  if (whereParamAnd) queryParams = whereParamAnd;

  const { whereDateCondition, whereDateParams } = pool.buildDateFilter(
    "a.schedule_date",
    searchParams.dateType,
    searchParams.dateValue,
    queryParams
  );
  if (whereDateParams) queryParams = whereDateParams;

  const whereParts = [];

  whereParts.push("a.deleted_at IS NULL");

  if (Array.isArray(whereConditions) && whereConditions.length > 0) {
    const joined = whereConditions.join(" AND ");
    const norm = normalizeClause(joined);
    if (norm) whereParts.push(norm);
  } else if (typeof whereConditions === "string" && whereConditions.trim()) {
    const norm = normalizeClause(whereConditions);
    if (norm) whereParts.push(norm);
  }

  if (whereOrConditions && String(whereOrConditions).trim()) {
    const norm = normalizeClause(whereOrConditions);
    if (norm) whereParts.push(norm);
  }

  if (whereDateCondition && String(whereDateCondition).trim()) {
    const norm = normalizeClause(whereDateCondition);
    if (norm) whereParts.push(norm);
  }

  const whereClause =
    whereParts.length > 0 ? `WHERE ${whereParts.join(" AND ")}` : "";

  const queryText = `
    SELECT 
      COUNT(*) OVER() AS total_data, 
      a.*, 
      b.shift_name,
      b.start_time,
      b.end_time
    FROM schedule a
    LEFT JOIN m_shift b ON a.shift_id = b.shift_id
    ${whereClause}
    ORDER BY a.schedule_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 };
};

// Get by ID
const getScheduleByIdDb = async (id) => {
  const queryText = `
    SELECT 
      a.*, 
      b.shift_name,
      b.start_time,
      b.end_time
    FROM schedule a
    LEFT JOIN m_shift b ON a.shift_id = b.shift_id
    WHERE a.schedule_id = $1 AND a.deleted_at IS NULL
  `;
  const result = await pool.query(queryText, [id]);
  return result.recordset?.[0] || null;
};

// Insert (bisa multi hari)
const insertScheduleDb = async (store) => {
  const nextDays = Number(store.next_day ?? 0);
  const insertedRecords = [];

  for (let i = 0; i <= nextDays; i++) {
    const nextDate = new Date(store.schedule_date);
    nextDate.setDate(nextDate.getDate() + i);

    const formatted = formattedDate(nextDate);
    const newStore = { ...store, schedule_date: formatted };
    delete newStore.next_day;

    const { query: queryText, values } = pool.buildDynamicInsert("schedule", newStore);
    const result = await pool.query(queryText, values);
    const insertedId = result.recordset?.[0]?.inserted_id;

    if (insertedId) {
      const record = await getScheduleByIdDb(insertedId);
      insertedRecords.push(record);
    }
  }

  return insertedRecords;
};

// Update
const updateScheduleDb = async (id, data) => {
  const store = { ...data };
  const whereData = { schedule_id: id };

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

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

// Soft delete
const deleteScheduleDb = async (id, deletedBy) => {
  const queryText = `
    UPDATE schedule
    SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
    WHERE schedule_id = $2 AND deleted_at IS NULL
  `;
  await pool.query(queryText, [deletedBy, id]);
  return true;
};

module.exports = {
  getAllScheduleDb,
  getScheduleByIdDb,
  insertScheduleDb,
  updateScheduleDb,
  deleteScheduleDb,
};
