const fs = require("fs");
const path = require("path");

const {
  searchFlights,
} = require("../services/lowFareSearchJson");

/**
 * Generate unique TraceId
 */
const generateTraceId = () => {
  return `BOBROS-${Date.now()}`;
};

/**
 * Save request/response logs
 */
const saveDebugJson = async (fileName, data) => {
  try {
    const debugDir = path.resolve(__dirname, "..", "debug-json");

    if (!fs.existsSync(debugDir)) {
      fs.mkdirSync(debugDir, { recursive: true });
    }

    await fs.promises.writeFile(
      path.join(debugDir, fileName),
      JSON.stringify(data, null, 2)
    );
  } catch (err) {
    console.error(`[DEBUG-LOG-ERR] ${err.message}`);
  }
};

exports.searchLowFareJson = async (req, res) => {
  const traceId = generateTraceId();

  console.log(`[${traceId}] Starting JSON Low Fare Search`);

  try {
    const { tripType, segments, passengers } = req.body;

    // Validation
    if (!tripType) {
      return res.status(400).json({
        success: false,
        traceId,
        error: "tripType is required",
      });
    }

    if (!segments || !Array.isArray(segments) || segments.length === 0) {
      return res.status(400).json({
        success: false,
        traceId,
        error: "segments array is required",
      });
    }

    if (!passengers) {
      return res.status(400).json({
        success: false,
        traceId,
        error: "passengers object is required",
      });
    }

    // Save frontend request
    await saveDebugJson(
      `SearchRequest-${traceId}.json`,
      req.body
    );

    // Call service
    const response = await searchFlights(req.body, traceId);

    // Save Travelport response
    await saveDebugJson(
      `SearchResponse-${traceId}.json`,
      response.data
    );

    return res.status(200).json({
      success: true,
      traceId,
      data: response.data,
    });
  } catch (err) {
    console.error(`[${traceId}] JSON Search Error:`, err.message);

    return res.status(500).json({
      success: false,
      traceId,
      error: err.response?.data || err.message,
    });
  }
};

