using Apollinare.Domain.Entities;
using Apollinare.Infrastructure.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Apollinare.API.Controllers;

[ApiController]
[Route("api/[controller]")]
public class LocationController : ControllerBase
{
    private readonly AppollinareDbContext _context;

    public LocationController(AppollinareDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public async Task<ActionResult<IEnumerable<Location>>> GetLocation([FromQuery] string? search, [FromQuery] bool? attivo)
    {
        var query = _context.Location.AsQueryable();

        if (!string.IsNullOrEmpty(search))
            query = query.Where(l => l.Nome.Contains(search) ||
                                     (l.Citta != null && l.Citta.Contains(search)));

        if (attivo.HasValue)
            query = query.Where(l => l.Attivo == attivo.Value);

        return await query.OrderBy(l => l.Nome).ToListAsync();
    }

    [HttpGet("{id}")]
    public async Task<ActionResult<Location>> GetLocation(int id)
    {
        var location = await _context.Location
            .Include(l => l.Eventi)
            .FirstOrDefaultAsync(l => l.Id == id);

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

        return location;
    }

    [HttpPost]
    public async Task<ActionResult<Location>> CreateLocation(Location location)
    {
        location.CreatedAt = DateTime.UtcNow;
        _context.Location.Add(location);
        await _context.SaveChangesAsync();

        return CreatedAtAction(nameof(GetLocation), new { id = location.Id }, location);
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> UpdateLocation(int id, Location location)
    {
        if (id != location.Id)
            return BadRequest();

        location.UpdatedAt = DateTime.UtcNow;
        _context.Entry(location).State = EntityState.Modified;

        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!await _context.Location.AnyAsync(l => l.Id == id))
                return NotFound();
            throw;
        }

        return NoContent();
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteLocation(int id)
    {
        var location = await _context.Location.FindAsync(id);
        if (location == null)
            return NotFound();

        _context.Location.Remove(location);
        await _context.SaveChangesAsync();

        return NoContent();
    }
}
