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

// Get error codes by brand ID
const getErrorCodesByBrandIdDb = async (brandId) => {
  const queryText = `
    SELECT
      a.*
    FROM brand_code a
    WHERE a.brand_id = $1 AND a.deleted_at IS NULL
    ORDER BY a.error_code_id
  `;
  const result = await pool.query(queryText, [brandId]);
  return result.recordset;
};

const createErrorCodeDb = async (brandId, data) => {
  const store = {
    brand_id: brandId,
    error_code: data.error_code,
    error_code_name: data.error_code_name,
    error_code_description: data.error_code_description,
    error_code_color: data.error_code_color,
    path_icon: data.path_icon,
    is_active: data.is_active,
    created_by: data.created_by
  };

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

const updateErrorCodeDb = async (brandId, errorCode, data) => {
  const store = { ...data };
  const whereData = {
    brand_id: brandId,
    error_code: errorCode
  };

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

const deleteErrorCodeDb = async (brandId, errorCode, deletedBy) => {
  const queryText = `
    UPDATE brand_code
    SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
    WHERE brand_id = $2 AND error_code = $3 AND deleted_at IS NULL
  `;
  await pool.query(queryText, [deletedBy, brandId, errorCode]);
  return true;
};

const getErrorCodeByIdDb = async (error_code_id) => {
  const queryText = `
    SELECT
      a.*
    FROM brand_code a
    WHERE a.error_code_id = $1 AND a.deleted_at IS NULL
  `;
  const result = await pool.query(queryText, [error_code_id]);
  return result.recordset[0];
};

module.exports = {
  getErrorCodesByBrandIdDb,
  getErrorCodeByIdDb,
  createErrorCodeDb,
  updateErrorCodeDb,
  deleteErrorCodeDb,
};