using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using System.Collections.Generic;
using System.Threading.Tasks;
using GestionIntegral.Api.Dtos.Anomalia;
using GestionIntegral.Api.Services.Anomalia;

namespace GestionIntegral.Api.Controllers.Anomalia
{
    [Route("api/alertas")]
    [ApiController]
    [Authorize]
    public class AlertasController : ControllerBase
    {
        private readonly IAlertaService _alertaService;

        public AlertasController(IAlertaService alertaService)
        {
            _alertaService = alertaService;
        }

        // GET: api/alertas
        [HttpGet]
        [ProducesResponseType(typeof(IEnumerable<AlertaGenericaDto>), StatusCodes.Status200OK)]
        public async Task<IActionResult> GetAlertasNoLeidas()
        {
            var alertas = await _alertaService.ObtenerAlertasNoLeidasAsync();
            return Ok(alertas);
        }

        // POST: api/alertas/{idAlerta}/marcar-leida
        [HttpPost("{idAlerta:int}/marcar-leida")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> MarcarComoLeida(int idAlerta)
        {
            var (exito, error) = await _alertaService.MarcarComoLeidaAsync(idAlerta);
            if (!exito)
            {
                return NotFound(new { message = error });
            }
            return NoContent();
        }

        // POST: api/alertas/marcar-grupo-leido
        [HttpPost("marcar-grupo-leido")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> MarcarGrupoLeido([FromBody] MarcarGrupoLeidoRequestDto request)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var (exito, error) = await _alertaService.MarcarGrupoComoLeidoAsync(request.TipoAlerta, request.IdEntidad);
            if (!exito)
            {
                return BadRequest(new { message = error });
            }
            return NoContent();
        }
    }

    // DTO para el cuerpo del request de marcar grupo
    public class MarcarGrupoLeidoRequestDto 
    {
        [System.ComponentModel.DataAnnotations.Required]
        public string TipoAlerta { get; set; } = string.Empty;

        [System.ComponentModel.DataAnnotations.Required]
        public int IdEntidad { get; set; }
    }
}