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

const getAllNotificationErrorSparepartDb = 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.brand_sparepart_id",
      "a.contact_id",
      "b.sparepart_name",
      "d.contact_name",
      "d.contact_type"
    ],
    searchParams.criteria,
    queryParams
  );

  if (whereParamOr) queryParams = whereParamOr;

  const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
    [
      { column: "a.brand_sparepart_id", param: searchParams.name, type: "int" },
      { column: "a.contact_id", param: searchParams.code, type: "int" },
      { column: "a.unit", param: searchParams.unit, type: "string" },
      { column: "b.sparepart_name", param: searchParams.device, type: "string" },
      { column: "d.contact_name", param: searchParams.device, type: "string" },
      { column: "d.contact_type", param: searchParams.device, type: "string" },
    ],
    queryParams
  );

  if (whereParamAnd) queryParams = whereParamAnd;

  const queryText = `
    SELECT 
      COUNT(*) OVER() AS total_data, 
      a.*, 
      b.sparepart_name, 
      b.brand_sparepart_description,
      d.contact_name,
      d.contact_type
    FROM notification_error_sparepart a

    LEFT JOIN brand_sparepart b ON a.brand_sparepart_id = b.brand_sparepart_id

    LEFT JOIN contact d on a.contact_id = d.contact_id

    WHERE a.deleted_at IS NULL
      ${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
      ${whereOrConditions ? ` ${whereOrConditions}` : ""}
    ORDER BY a.notification_error_sparepart_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 getNotificationErrorSparepartByIdDb = async (id) => {
  const queryText = `
    SELECT
      a.*, 
      b.sparepart_name, 
      b.brand_sparepart_description,
      d.contact_name,
      d.contact_type
    FROM notification_error_sparepart a
    LEFT JOIN brand_sparepart b ON a.brand_sparepart_id = b.brand_sparepart_id
    LEFT JOIN contact d on a.contact_id = d.contact_id
    WHERE a.notification_error_sparepart_id = $1 
      AND a.deleted_at IS NULL
  `;
  const result = await pool.query(queryText, [id]);
  return result.recordset?.[0] || null;
};


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

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

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

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

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

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

module.exports = {
  getAllNotificationErrorSparepartDb,
  getNotificationErrorSparepartByIdDb,
  createNotificationErrorSparepartDb,
  updateNotificationErrorSparepartDb,
  deleteNotificationErrorSparepartDb,
};
