// engines/sort.engine.js

exports.sortFlights = (flights, sortBy = "PRICE") => {
    if (!Array.isArray(flights)) return [];

    switch (sortBy) {

        // 💰 Cheapest first
        case "PRICE":
            return flights.sort((a, b) => a.price - b.price);

        // ⏱ Shortest duration
        case "DURATION":
            return flights.sort((a, b) => a.totalDuration - b.totalDuration);

        // 🕓 Earliest departure
        case "DEPARTURE":
            return flights.sort((a, b) =>
                a.departureTime.localeCompare(b.departureTime)
            );

        // 🕔 Earliest arrival
        case "ARRIVAL":
            return flights.sort((a, b) =>
                a.arrivalTime.localeCompare(b.arrivalTime)
            );

        // 🔥 Recommended (advanced logic)
        case "RECOMMENDED":
            return flights.sort((a, b) => {
                // Score based sorting
                const scoreA = getScore(a);
                const scoreB = getScore(b);
                return scoreB - scoreA; // higher score first
            });

        default:
            return flights;
    }
};

// 🔥 Smart scoring (like MakeMyTrip)
function getScore(flight) {
    let score = 0;

    // Lower price → higher score
    score += (10000 - flight.price) * 0.4;

    // Short duration → higher score
    score += (1000 - flight.totalDuration) * 0.3;

    // Fewer stops → higher score
    score += (2 - flight.stops) * 100 * 0.3;

    return score;
}