// src/middleware/validateRequest.js

function lowFareSearchValidationRules(req, res, next) {
  const errors = [];

  const { flights, passengers, offersPerPage, carriers } = req.body;

  // ─────────────────────────────────────────────
  // Flights Validation
  // ─────────────────────────────────────────────

  if (!Array.isArray(flights) || flights.length === 0) {
    errors.push({
      field: "flights",
      message: "flights must be a non-empty array",
    });
  } else {
    flights.forEach((flight, index) => {
      // FROM
      if (
        typeof flight.from !== "string" ||
        flight.from.length < 2 ||
        flight.from.length > 5
      ) {
        errors.push({
          field: `flights[${index}].from`,
          message:
            'Each flight must have a valid "from" IATA code (e.g. "DEN")',
        });
      } else {
        flight.from = flight.from.toUpperCase();
      }

      // TO
      if (
        typeof flight.to !== "string" ||
        flight.to.length < 2 ||
        flight.to.length > 5
      ) {
        errors.push({
          field: `flights[${index}].to`,
          message:
            'Each flight must have a valid "to" IATA code (e.g. "ORD")',
        });
      } else {
        flight.to = flight.to.toUpperCase();
      }

      // DATE
      if (
        !/^\d{4}-\d{2}-\d{2}$/.test(flight.departureDate)
      ) {
        errors.push({
          field: `flights[${index}].departureDate`,
          message:
            "departureDate must be in YYYY-MM-DD format",
        });
      }
    });
  }

  // ─────────────────────────────────────────────
  // Passengers Validation
  // ─────────────────────────────────────────────

  if (passengers !== undefined) {
    if (!Array.isArray(passengers) || passengers.length === 0) {
      errors.push({
        field: "passengers",
        message:
          "passengers must be a non-empty array if provided",
      });
    } else {
      passengers.forEach((pax, index) => {
        // TYPE
        if (
          pax.type &&
          !["ADT", "CNN","CHD", "INF", "SRC"].includes(pax.type)
        ) {
          errors.push({
            field: `passengers[${index}].type`,
            message:
              "Passenger type must be ADT, CHD, INF, or SRC",
          });
        }

        // COUNT
        if (
          pax.count !== undefined &&
          (!Number.isInteger(pax.count) ||
            pax.count < 1 ||
            pax.count > 9)
        ) {
          errors.push({
            field: `passengers[${index}].count`,
            message:
              "Passenger count must be between 1 and 9",
          });
        }

        // AGE
        if (
          pax.age !== undefined &&
          (!Number.isInteger(pax.age) ||
            pax.age < 0 ||
            pax.age > 120)
        ) {
          errors.push({
            field: `passengers[${index}].age`,
            message:
              "Passenger age must be between 0 and 120",
          });
        }
      });
    }
  }

  // ─────────────────────────────────────────────
  // offersPerPage
  // ─────────────────────────────────────────────

  if (
    offersPerPage !== undefined &&
    (!Number.isInteger(offersPerPage) ||
      offersPerPage < 1 ||
      offersPerPage > 100)
  ) {
    errors.push({
      field: "offersPerPage",
      message:
        "offersPerPage must be between 1 and 100",
    });
  }

  // ─────────────────────────────────────────────
  // Carriers Validation
  // ─────────────────────────────────────────────

  if (
    carriers?.preferred !== undefined &&
    !Array.isArray(carriers.preferred)
  ) {
    errors.push({
      field: "carriers.preferred",
      message:
        "carriers.preferred must be an array of carrier codes",
    });
  }

  if (
    carriers?.excluded !== undefined &&
    !Array.isArray(carriers.excluded)
  ) {
    errors.push({
      field: "carriers.excluded",
      message:
        "carriers.excluded must be an array of carrier codes",
    });
  }

  // ─────────────────────────────────────────────
  // Final Error Response
  // ─────────────────────────────────────────────

  if (errors.length > 0) {
    return res.status(400).json({
      success: false,
      message: "Validation failed",
      errors,
    });
  }

  next();
}

module.exports = {
  lowFareSearchValidationRules,
};