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

// Get all Contact
const getAllContactDb = 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.contact_name",
      "a.contact_type",
    ],
    searchParams.criteria,
    queryParams
  );

  if (whereParamOr) queryParams = whereParamOr;

  const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
    [
      { column: "a.contact_name", param: searchParams.name, type: "string" },
      { column: "a.contact_type", param: searchParams.code, type: "string" },
    ],
    queryParams
  );

  if (whereParamAnd) queryParams = whereParamAnd;

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

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

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

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

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

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

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

module.exports = {
  getAllContactDb,
  getContactByIdDb,
  createContactDb,
  updateContactDb,
  deleteContactDb,
};
