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

// Get all status
const getAllStatusDb = async (searchParams = {}) => {
  let queryParams = [];

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

  // Search
  const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
    ["a.status_name", "a.status_description"],
    searchParams.criteria,
    queryParams
  );

  queryParams = whereParamOr ? whereParamOr : queryParams;

  // Filter
  const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
    [
      { column: "a.status_number", param: searchParams.number, type: "number" },
      { column: "a.is_active", param: searchParams.is_active, type: "boolean" },
    ],
    queryParams
  );

  queryParams = whereParamAnd ? whereParamAnd : queryParams;

  const queryText = `
    SELECT 
      COUNT(*) OVER() AS total_data,
      a.*
    FROM m_status a
    WHERE a.deleted_at IS NULL
      ${whereConditions.length > 0 ? `AND ${whereConditions.join(' AND ')}` : ''}
      ${whereOrConditions ? whereOrConditions : ''}
    ORDER BY a.status_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 getStatusByIdDb = async (id) => {
  const queryText = `
    SELECT *
    FROM m_status a
    WHERE a.status_id = $1 AND a.deleted_at IS NULL
  `;
  const result = await pool.query(queryText, [id]);
  return result.recordset;
};

// Check if status_number already exists
const checkStatusNumberExistsDb = async (status_number) => {
  const queryText = `
    SELECT 1
    FROM m_status
    WHERE status_number = $1 AND deleted_at IS NULL
  `;
  const result = await pool.query(queryText, [status_number]);
  return result.recordset.length > 0;
};


const createStatusDb = async (data) => {
  const { query: queryText, values } = pool.buildDynamicInsert(
    "m_status",
    data
  );
  const result = await pool.query(queryText, values);
  const insertedId = result.recordset[0]?.inserted_id;
  return insertedId ? await getStatusByIdDb(insertedId) : null;
};

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

  const { query: queryText, values } = pool.buildDynamicUpdate(
    "m_status",
    store,
    whereData
  );
  await pool.query(`${queryText} AND deleted_at IS NULL`, values);
  return getStatusByIdDb(id);
};

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

module.exports = {
  getAllStatusDb,
  getStatusByIdDb,
  createStatusDb,
  updateStatusDb,
  deleteStatusDb,
  checkStatusNumberExistsDb,
};
