using Microsoft.AspNetCore.Mvc;
using SIGCM.Domain.Entities;
using SIGCM.Infrastructure.Repositories;

namespace SIGCM.API.Controllers;

[ApiController]
[Route("api/[controller]")]
[Microsoft.AspNetCore.Authorization.Authorize]
public class ClientsController : ControllerBase
{
  private readonly ClientRepository _repo;
  private readonly AuditRepository _auditRepo;

  public ClientsController(ClientRepository repo, AuditRepository auditRepo)
  {
    _repo = repo;
    _auditRepo = auditRepo;
  }

  [HttpGet("search")]
  public async Task<IActionResult> Search([FromQuery] string q)
  {
    if (string.IsNullOrWhiteSpace(q)) return Ok(new List<object>());
    var clients = await _repo.SearchAsync(q);
    return Ok(clients);
  }

  [HttpGet]
  public async Task<IActionResult> GetAll()
  {
    var clients = await _repo.GetAllWithStatsAsync();
    return Ok(clients);
  }

  [HttpPut("{id}")]
  public async Task<IActionResult> Update(int id, Client client)
  {
    if (id != client.Id) return BadRequest("ID de URL no coincide con el cuerpo");
    await _repo.UpdateAsync(client);

    // Audit Log
    var userIdClaim = User.FindFirst("Id")?.Value;
    if (int.TryParse(userIdClaim, out int userId))
    {
      await _auditRepo.AddLogAsync(new AuditLog
      {
        UserId = userId,
        Action = "UPDATE_CLIENT",
        EntityId = id,
        EntityType = "Client",
        Details = $"Cliente {client.Name} actualizado (DNI/CUIT: {client.DniOrCuit})",
        CreatedAt = DateTime.UtcNow
      });
    }

    return NoContent();
  }

  [HttpGet("{id}/summary")]
  public async Task<IActionResult> GetSummary(int id)
  {
    var summary = await _repo.GetClientSummaryAsync(id);
    if (summary == null) return NotFound();
    return Ok(summary);
  }
}