Skip to content
Snippets Groups Projects
FlightController.cs 2.81 KiB
Newer Older
using FlightMicroservice.Models;
using FlightMicroservice.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace FlightMicroservice.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class FlightController : ControllerBase
    {
        private readonly IFlightService flightService;

        public FlightController(IFlightService flightService)
        {
            this.flightService = flightService;
        }

        [HttpGet()]
        public ActionResult GetFlights(int? airlineId = null, string? origin = null, string? destination = null, DateTime? departureTime = null, DateTime? arrivalTime = null)
            List<Flight> flights = flightService.GetFlights(airlineId, origin, destination, departureTime, arrivalTime);
            if (flights == null)
                return BadRequest();

            return Ok(flights);
        }

        [HttpGet("{id}")]
        public ActionResult GetFlight(int id)
        {
            Flight? flight = flightService.GetFlight(id);
            if (flight == null)
                return NotFound($"Could Not Find a Flight with Id: {id}");

            return Ok(flight);
        }

        [Authorize]
        [HttpPost()]
        public ActionResult AddFlight([FromBody] FlightCreationModel model)
        {
            string? airlineIdValue = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            if (!int.TryParse(airlineIdValue, out int airlineId))
                return BadRequest("Unable to get Airline Id from Token");

            Flight flight = flightService.CreateFlight(
                airlineId, model.Origin, model.Destination, model.DepartureTime, model.ArrivalTime,
                model.EconomyCapacity, model.BusinessCapacity, model.EconomyPrice, model.BusinessPrice);

            if (flight == null)
                return BadRequest("Failed to create the flight.");

            return Ok(flight);
        }

        [HttpGet("{flightId}/capacity")]
        public ActionResult GetFlightCapacity([FromRoute] int flightId, [FromQuery] ClassType classType)
        {
            Flight? flight = flightService.GetFlight(flightId);
            if (flight == null)
                return NotFound($"Could Not Find a Flight with Id: {flightId}");

            int seatCapacity = classType == ClassType.BUSINESS ? flight.BusinessCapacity : flight.EconomyCapacity;

            return Ok(seatCapacity);
        [HttpGet("{flightId}/seats")]
        public IActionResult GetFlightSeats([FromRoute] int flightId)
        {
            List<Seat>? seats = flightService.GetSeatsByFlightId(flightId);
            if (seats == null)
                return NotFound($"Flight with Id {flightId} does not exist or could not be found.");

            return Ok(seats);
        }