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

exports.checkAvailability = async (req, res) => {
  try {
    const { lat, lng, checkIn, checkOut, rooms, adults, children, radius } = req.body;

    const payload = {
      "stayDetails": {
        "checkInDateLocal": `${checkIn}`,
        "checkOutDateLocal": `${checkOut}`,
        "rooms": rooms,  
        "guests": {
          "adults": adults,
          "children": children,
        },
      },
      "propertyFilter": {
        "aggregators": ["TVPT"],
        "location": {
          "type": "coordinates",
          "details": {
            "latitude": lat,
            "longitude": lng,
          },
          "radius": {
            "value": radius,
            "unit": "km",
          },
        },
      },
    };

    const endPoint = "/search/searchcomplete";

    // first call in the flow -> no incoming traceId, service mints a BOBROS- id
    const { data, traceId } = await callHotelAPI.callStayService(payload, endPoint);
    console.log("returning response, traceId:", traceId);

    res.set("TVP-Trace-Id", traceId);
    res.status(200).json(data);
  } 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 });
  }
};