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

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

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

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

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

            return Ok(item);
        }

        // POST: api/stops
        [HttpPost]
        public async Task<IActionResult> Create([FromBody] Stop stop)
        {
            _context.Stops.Add(stop);
            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(Get), new { id = stop.StopId }, stop);
        }

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

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

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

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

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