package com.example.skychasemk.services;

import com.example.skychasemk.model.Destination;
import com.example.skychasemk.model.Flight;
import com.example.skychasemk.repository.DestinationRepository;
import com.example.skychasemk.repository.FlightRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@Service
public class FlightService {

    @Autowired
    private FlightRepository flightRepository;

    @Autowired
    private DestinationRepository destinationRepository;

    public Optional<Flight> getFlightById(Long flightID) {
        return flightRepository.findById(flightID);
    }

    public Flight saveFlight(Flight flight) {
        return flightRepository.save(flight);
    }

    public Flight updateFlight(Long flightID, Flight flight) {
        if (flightRepository.existsById(flightID)) {
            flight.setFlightID(flightID);
            return flightRepository.save(flight);
        } else {
            throw new RuntimeException("Flight not found with id " + flightID);
        }
    }

    public void deleteFlight(Long flightID) {
        flightRepository.deleteById(flightID);
    }



    public List<Flight> getFlights(String departureCity, String destination, LocalDate departureDate, LocalDate returnDate) {
        List<Destination> destinations = destinationRepository.findAll();

        Integer departureID = Destination.getAirportID(departureCity, destinations);
        Integer destinationID = Destination.getAirportID(destination, destinations);

        return flightRepository.findFlights(departureID, destinationID, departureDate);
    }

}

