// services/paymentService.js
const { buildValidateBody } = require("./buildValidateBody");
const { sendToBBPS } = require("./bbpsIntegrationService");

async function validatePayment(reqBody) {
  const built = await buildValidateBody(reqBody);

  if (built.flow === "error" || built.flow === "adhoc") {
    return built;
  }

  const path = "billpay/validate"; // adjust if BBPS endpoint differs
  const bbpsResult = await sendToBBPS({ path, payload: built.body, lineEndings: "crlf" });

  if (!bbpsResult.success) {
    return {
      flow: "error",
      error: {
        code: bbpsResult.code || 5020,
        message: bbpsResult.message || "BBPS call failed",
        details: bbpsResult.details || null,
      },
      traceId: bbpsResult.traceId,
    };
  }

  return {
    flow: "validate",
    data: bbpsResult.data,
    traceId: bbpsResult.traceId,
  };
}

module.exports = { validatePayment };
