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

// Get all Contact
const getAllBrandSparepartsDb = 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.sparepart_name",
      "a.brand_sparepart_description",
      "a.is_active"
    ],
    searchParams.criteria,
    queryParams
  );

  if (whereParamOr) queryParams = whereParamOr;

  const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
    [
      { column: "a.sparepart_name", param: searchParams.sparepart_name, type: "string" },
      { column: "a.brand_sparepart_description", param: searchParams.brand_sparepart_description, type: "string" },
       { column: "a.is_active", param: searchParams.code, type: "int" },
    ],
    queryParams
  );

  if (whereParamAnd) queryParams = whereParamAnd;

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

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

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


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

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

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


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

const checkBrandSparepartNameExistsDb = async (brandSparePartName, excludeId = null) => {
  let queryText = `
    SELECT brand_sparepart_id
    FROM brand_sparepart
    WHERE sparepart_name = $1 AND deleted_at IS NULL
  `;
  let values = [brandSparePartName];

  if (excludeId) {
    queryText += ` AND brand_sparepart_id != $2`;
    values.push(excludeId);
  }

  const result = await pool.query(queryText, values);
  return result.recordset.length > 0;
};

module.exports = {
  getAllBrandSparepartsDb,
  getBrandSparepartByIdDb,
  createBrandSparepartDb,
  updateBrandSparepartDb,
  deleteBrandSparepartDb,
  checkBrandSparepartNameExistsDb
};
