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

// Get all sub sections
const getAllSubSectionsDb = async (searchParams = {}) => {
  let queryParams = [];

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

  // OR condition (pencarian bebas)
  const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
    ["a.plant_sub_section_code", "a.plant_sub_section_name"],
    searchParams.criteria,
    queryParams
  );

  queryParams = whereParamOr ?? queryParams;

  // AND condition (filter spesifik)
  const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
    [
      { column: "a.plant_sub_section_code", param: searchParams.code, type: "string" },
      { column: "a.plant_sub_section_name", param: searchParams.name, type: "string" },
    ],
    queryParams
  );

  queryParams = whereParamAnd ?? queryParams;

  // Query utama
  const queryText = `
    SELECT COUNT(*) OVER() AS total_data, a.*
    FROM m_plant_sub_section a
    WHERE a.deleted_at IS NULL
    ${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
    ${whereOrConditions ? whereOrConditions : ""}
    ORDER BY a.plant_sub_section_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 sub section by ID
const getSubSectionByIdDb = async (id) => {
  const queryText = `
    SELECT a.*
    FROM m_plant_sub_section a
    WHERE a.plant_sub_section_id = $1 AND a.deleted_at IS NULL
  `;
  const result = await pool.query(queryText, [id]);
  return result.recordset;
};

// Create new sub section
const createSubSectionDb = async (data) => {
  // Generate kode otomatis
  const newCode = await pool.generateKode("SUB", "m_plant_sub_section", "plant_sub_section_code");

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

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

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

// Update sub section
const updateSubSectionDb = async (id, data) => {
  const store = { ...data };
  const whereData = { plant_sub_section_id: id };

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

  return getSubSectionByIdDb(id);
};

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

module.exports = {
  getAllSubSectionsDb,
  getSubSectionByIdDb,
  createSubSectionDb,
  updateSubSectionDb,
  deleteSubSectionDb,
};
