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

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

// Create solution for error code
const createSolutionDb = async (errorCodeId, data) => {
  const store = {
    error_code_id: errorCodeId,
    solution_name: data.solution_name,
    type_solution: data.type_solution,
    text_solution: data.text_solution,
    path_solution: data.path_solution,
    is_active: data.is_active,
    created_by: data.created_by
  };

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

// Update solution
const updateSolutionDb = async (solutionId, data) => {
  const store = { ...data };
  const whereData = { brand_code_solution_id: solutionId };

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

// Soft delete solution
const deleteSolutionDb = async (solutionId, deletedBy) => {
  const queryText = `
    UPDATE brand_code_solution
    SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
    WHERE brand_code_solution_id = $2 AND deleted_at IS NULL
  `;
  await pool.query(queryText, [deletedBy, solutionId]);
  return true;
};

module.exports = {
  getSolutionsByErrorCodeIdDb,
  createSolutionDb,
  updateSolutionDb,
  deleteSolutionDb,
};