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

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

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

        // GET: api/lines
        [HttpGet]
        public async Task<IActionResult> GetLines()
        {
            var lines = await _context.Lines
                .Include(x => x.Passengers)
                .Include(x => x.Stops)
                .ToListAsync();

            return Ok(lines);
        }

        // GET: api/lines/5
        [HttpGet("{id}")]
        public async Task<IActionResult> GetLine(int id)
        {
            var line = await _context.Lines
                .Include(x => x.Passengers)
                .Include(x => x.Stops)
                .FirstOrDefaultAsync(x => x.Id == id);

            if (line == null)
                return NotFound();

            return Ok(line);
        }

        // POST: api/lines
        [HttpPost]
        public async Task<IActionResult> CreateLine([FromBody] Line line)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            _context.Lines.Add(line);
            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(GetLine), new { id = line.Id }, line);
        }

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

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

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

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

            _context.Lines.Remove(line);
            await _context.SaveChangesAsync();

            return NoContent();
        }
    }
}
