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

// Get all units
const getAllUnitsDb = 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.unit_code", "a.unit_name"],
    searchParams.criteria,
    queryParams
  );

  queryParams = whereParamOr ? whereParamOr : queryParams;

  // Filter
  const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
    [
      { column: "a.unit_code", param: searchParams.code, type: "string" },
      { column: "a.unit_name", param: searchParams.name, type: "string" },
      { column: "a.tag_id", param: searchParams.tag, type: "number" },
      { column: "a.is_active", param: searchParams.status, type: "string" },
    ],
    queryParams
  );

  queryParams = whereParamAnd ? whereParamAnd : queryParams;

  const queryText = `
    SELECT
      COUNT(*) OVER() AS total_data,
      a.*,
      COALESCE(a.unit_code, '') + ' - ' + COALESCE(a.unit_name, '') AS unit_code_name
    FROM m_unit a
    WHERE a.deleted_at IS NULL
      ${whereConditions.length > 0 ? `AND ${whereConditions.join(" AND ")}` : ""}
      ${whereOrConditions ? whereOrConditions : ""}
    ORDER BY a.unit_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 unit by ID
const getUnitByIdDb = async (id) => {
  const queryText = `
    SELECT 
      a.*,
      COALESCE(a.unit_code, '') + ' - ' + COALESCE(a.unit_name, '') AS unit_code_name
    FROM m_unit a
    WHERE a.unit_id = $1 AND a.deleted_at IS NULL
  `;
  const result = await pool.query(queryText, [id]);
  return result.recordset;
};

// Create unit
const createUnitDb = async (data) => {
  const newCode = await pool.generateKode("UNT", "m_unit", "unit_code");

  const store = {
    ...data,
    unit_code: newCode,
  };

  const { query: queryText, values } = pool.buildDynamicInsert("m_unit", store);
  const result = await pool.query(queryText, values);
  const insertedId = result.recordset[0]?.inserted_id;
  return insertedId ? await getUnitByIdDb(insertedId) : null;
};

// Update unit
const updateUnitDb = async (id, data) => {
  const store = { ...data };
  const whereData = { unit_id: id };

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

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

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

// Export
module.exports = {
  getAllUnitsDb,
  getUnitByIdDb,
  createUnitDb,
  updateUnitDb,
  deleteUnitDb,
};