using FlightMicroservice.Models;
using Microsoft.EntityFrameworkCore;

namespace FlightMicroservice.Services
{
    public class SeatService : ISeatService
    {
        private readonly ApplicationDbContext dbContext;

        public SeatService(ApplicationDbContext dbContext)
        {
            this.dbContext = dbContext;
        }

        public List<Seat> GetSeats()
        {
            List<Seat> seats = dbContext.Seats.ToList();
            return seats;
        }

        public Seat? GetSeat(int id)
        {
            Seat? seat = dbContext.Seats.FirstOrDefault(seat => seat.Id == id);
            return seat;
        }

        public void BookSeat(int id)
        {
            int affectedRows = dbContext.Seats
                .Where(seat => seat.Id == id)
                .ExecuteUpdate(setters => setters
                    .SetProperty(seat => seat.IsAvailable, false));
            
            dbContext.SaveChanges();
            
            if (affectedRows == 0)
                throw new KeyNotFoundException($"A seat with the ID {id} was not found.");
        }

        public bool IsAvailable(int id)
        {
            Seat? seat = dbContext.Seats.FirstOrDefault(seat => seat.Id == id);
            if(seat == null)
                throw new KeyNotFoundException($"A seat with the ID {id} was not found.");

            return seat.IsAvailable;
        }
    }
}