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

// Get solutions by error code ID
const getSparePartnsByErrorCodeIdDb = async (errorCodeId) => {
  const queryText = `
    SELECT
      a.*
    FROM brand_sparepart a
    WHERE a.error_code_id = $1 AND a.deleted_at IS NULL
    ORDER BY a.brand_sparepart_id
  `;
  const result = await pool.query(queryText, [errorCodeId]);
  return result.recordset;
};

// Create solution for error code
const createSparePartDb = async (errorCodeId, data) => {
  const store = {
    error_code_id: errorCodeId,
    sparepart_name: data.sparepart_name,
    brand_sparepart_description: data.brand_sparepart_description,
    path_foto: data.path_foto,
    is_active: data.is_active,
    created_by: data.created_by
  };

  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;
};

// Update SparePartn
const updateSparePartDb = async (SparePartId, data) => {
  const store = { ...data };
  const whereData = { brand_sparepart_id: SparePartId };

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

// Soft delete SparePartn
const deleteSparePartDb = async (SparePartId, 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, SparePartId]);
  return true;
};

module.exports = {
  getSparePartnsByErrorCodeIdDb,
  createSparePartDb,
  updateSparePartDb,
  deleteSparePartDb,
};