const travelportJsonClient = require("../utils/travelportJsonClient");
const { getToken } = require("./token");
const {
  buildSearchPayload,
} = require("../utils/buildSearchPayload");
const {
  saveDebugJson,
  getTimestamp,
} = require("../utils/Debuglogger");

const searchFlights = async (requestData, traceId) => {
    const timestamp = getTimestamp();
  // Get OAuth token
  const token = await getToken();

  // Build Travelport payload
  const payload = buildSearchPayload(requestData, traceId);
  await saveDebugJson(
  `LowFareReq-${traceId}-${timestamp}.json`,
  payload
);

console.log(
  `[${traceId}] Request payload logged`
);

  console.log(`[${traceId}] Travelport Payload Built`);

  // Call Travelport API
  const response = await travelportJsonClient.post(
    process.env.TRAVELPORT_SEARCH_URL,
    payload,
    {
      headers: {
        Authorization: `Bearer ${token}`,
        traceId,
        XAUTH_TRAVELPORT_ACCESSGROUP:
      process.env.XAUTH_TRAVELPORT_ACCESSGROUP,
      },
    }
  );
  await saveDebugJson(
  `LowFareRsp-${traceId}-${timestamp}.json`,
  response.data
);

console.log(
  `[${traceId}] Response logged`
);
console.log(
  `[${traceId}] Travelport API Duration: ${response.duration}ms`
);

  console.log(`[${traceId}] Travelport Search Response Received`);

  return response;
};

module.exports = {
  searchFlights,
};