const pool = require('../../busapi/configs/dbConnection');

/**
 * Save BBPS validation API response
 * - Uses snake_case column names: customer_id, biller_id, validation_id, response_json
 * - Uses ON DUPLICATE KEY UPDATE to refresh stored JSON when same validation_id arrives
 */
async function saveValidationResponse(customerId, billerId, validationId, response) {
  if (!response) {
    console.warn("saveValidationResponse called with empty response - skipping save");
    return false;
  }

  try {
    const query = `
      INSERT INTO bbps_validation_responses
        (customer_id, biller_id, validation_id, response_json)
      VALUES (?, ?, ?, ?)
      ON DUPLICATE KEY UPDATE
        response_json = VALUES(response_json),
        customer_id = VALUES(customer_id),
        biller_id = VALUES(biller_id)
    `;

    const responseJson = typeof response === 'string' ? response : JSON.stringify(response);
    const values = [customerId || null, billerId || null, validationId || null, responseJson];

    // Using pool.execute / pool.query depending on your pool API
    await pool.query(query, values);

    console.log(`✅ Validation response saved (validation_id=${validationId}) for customer=${customerId} biller=${billerId}`);
    return true;
  } catch (err) {
    console.error("DB Error in saveValidationResponse:", err.message || err);
    return false;
  }
}
async function getValidationById(validationId) {
    const query = `
        SELECT *
        FROM bbps_validation_responses
        WHERE validation_id = ?
        LIMIT 1
    `;
    const [rows] = await pool.execute(query, [validationId]);
        if (!rows[0]) return null;

    const row = rows[0];

    try {
        row.response_json = JSON.parse(row.response_json);
    } catch (e) {
        console.error("❌ Failed to parse response_json:", e.message);
    }

    return row;

}



module.exports = { saveValidationResponse, getValidationById };
