require("dotenv").config();
const callHotelAPI = require("../services/callHotelAPI");

exports.getrules = async (req, res) => {
  try {
    const { rateKey } = req.body;

    // mid-flow step: it MUST carry the BOBROS- id from search.
    // accept from header (preferred) or body (handy for testing).
    const incomingTrace = req.get("TVP-Trace-Id") || req.body.traceId;
    if (!incomingTrace || !incomingTrace.trim()) {
      return res.status(400).json({
        error:
          "TVP-Trace-Id is required for the rules step. Send back the traceId you received from the search response.",
      });
    }

    const payload = {
      OfferQueryBuildFromCatalogOffering: {
        "@type": "OfferQueryBuildFromCatalogOffering",
        BuildFromCatalogOfferingHospitality: {
          "@type": "BuildFromCatalogOfferingHospitality",
          CatalogOfferingIdentifier: {
            value: `${rateKey}`,
            authority: "TVPT",
          },
        },
      },
    };

    const endPoint = `/rules/offershospitality/buildfromcatalogoffering`;

    const { data, traceId } = await callHotelAPI.callReservationService(
      payload,
      endPoint,
      incomingTrace
    );
    console.log("returning response, traceId:", traceId);

    res.set("TVP-Trace-Id", traceId);          // returned in the header
    res.status(200).json({ traceId, data });   // and visible in the body
  } catch (error) {
    if (error.code === "ECONNABORTED") {
      console.error("Request timed out");
      return res.status(504).json({ error: "Travelport request timed out" });
    }
    console.error("Error:", error.response?.data || error.message);
    res.status(500).json({ error: error.response?.data || error.message });
  }
};