using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using BUSNOW.Data;
using BUSNOW.Models;

namespace BUSNOW.Controllers.Api
{
    [ApiController]
    [Route("api/[controller]")]
    public class PassengersController : ControllerBase
    {
        private readonly AppDbContext _context;

        public PassengersController(AppDbContext context)
        {
            _context = context;
        }

        // GET: api/passengers
        [HttpGet]
        public async Task<IActionResult> GetAll()
        {
            var items = await _context.Passengers.ToListAsync();
            return Ok(items);
        }

        // GET: api/passengers/5
        [HttpGet("{id}")]
        public async Task<IActionResult> Get(int id)
        {
            var item = await _context.Passengers.FindAsync(id);
            if (item == null)
                return NotFound();

            return Ok(item);
        }

        // POST: api/passengers
        [HttpPost]
        public async Task<IActionResult> Create([FromBody] Passenger passenger)
        {
            _context.Passengers.Add(passenger);
            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(Get), new { id = passenger.Id }, passenger);
        }

        // PUT: api/passengers/5
        [HttpPut("{id}")]
        public async Task<IActionResult> Update(int id, [FromBody] Passenger passenger)
        {
            if (id != passenger.Id)
                return BadRequest("ID mismatch");

            _context.Entry(passenger).State = EntityState.Modified;

            await _context.SaveChangesAsync();
            return NoContent();
        }

        // DELETE: api/passengers/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(int id)
        {
            var item = await _context.Passengers.FindAsync(id);
            if (item == null)
                return NotFound();

            _context.Passengers.Remove(item);
            await _context.SaveChangesAsync();
            return NoContent();
        }
    }
}
