package com.example.skychasemk.controller;

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 com.example.skychasemk.services.FlightService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

import static com.example.skychasemk.model.Destination.getAirportID;

@RestController
@RequestMapping("/api/flights")
public class FlightController {

    @Autowired
    private FlightService flightService;
    @Autowired
    private FlightRepository flightRepository;
    @Autowired
    private DestinationRepository destinationRepository;

    @GetMapping
    public List<Flight> getAllFlights() {
        return flightRepository.findAll();
    }

    @GetMapping("/flights/{id}")
    public Optional<Flight> getFlightById(@PathVariable("id") Long flightID) {
        return flightService.getFlightById(flightID);
    }

    @GetMapping("/flight-search")
    public ResponseEntity<List<Flight>> searchFlights(
            @RequestParam String departureCity,
            @RequestParam String destination,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate departureDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate returnDate) {

        List<Destination> destinations = destinationRepository.findAll();

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



        List<Flight> flights = flightRepository.findFlights(departureID,destinationID, departureDate);
        return ResponseEntity.ok(flights);
    }

}

