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 ClientiController : ControllerBase
{
    private readonly AppollinareDbContext _context;

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

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

        if (!string.IsNullOrEmpty(search))
            query = query.Where(c => c.RagioneSociale.Contains(search) ||
                                     (c.Email != null && c.Email.Contains(search)));

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

        return await query.OrderBy(c => c.RagioneSociale).ToListAsync();
    }

    [HttpGet("{id}")]
    public async Task<ActionResult<Cliente>> GetCliente(int id)
    {
        var cliente = await _context.Clienti
            .Include(c => c.Eventi)
            .FirstOrDefaultAsync(c => c.Id == id);

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

        return cliente;
    }

    [HttpPost]
    public async Task<ActionResult<Cliente>> CreateCliente(Cliente cliente)
    {
        cliente.CreatedAt = DateTime.UtcNow;
        _context.Clienti.Add(cliente);
        await _context.SaveChangesAsync();

        return CreatedAtAction(nameof(GetCliente), new { id = cliente.Id }, cliente);
    }

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

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

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

        return NoContent();
    }

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

        _context.Clienti.Remove(cliente);
        await _context.SaveChangesAsync();

        return NoContent();
    }
}
