using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Dapper; using GestionIntegral.Api.Data; using GestionIntegral.Api.Dtos.Anomalia; using Microsoft.Extensions.Logging; namespace GestionIntegral.Api.Services.Anomalia { public class AlertaService : IAlertaService { private readonly DbConnectionFactory _dbConnectionFactory; private readonly ILogger _logger; public AlertaService(DbConnectionFactory dbConnectionFactory, ILogger logger) { _dbConnectionFactory = dbConnectionFactory; _logger = logger; } public async Task> ObtenerAlertasNoLeidasAsync() { // Apunta a la nueva tabla genérica 'Sistema_Alertas' var query = "SELECT * FROM Sistema_Alertas WHERE Leida = 0 ORDER BY FechaDeteccion DESC"; try { using (var connection = _dbConnectionFactory.CreateConnection()) { var alertas = await connection.QueryAsync(query); return alertas ?? Enumerable.Empty(); } } catch (System.Exception ex) { _logger.LogError(ex, "Error al obtener las alertas no leídas desde Sistema_Alertas."); return Enumerable.Empty(); } } public async Task<(bool Exito, string? Error)> MarcarComoLeidaAsync(int idAlerta) { var query = "UPDATE Sistema_Alertas SET Leida = 1 WHERE IdAlerta = @IdAlerta"; try { using (var connection = _dbConnectionFactory.CreateConnection()) { var result = await connection.ExecuteAsync(query, new { IdAlerta = idAlerta }); if (result > 0) { return (true, null); } return (false, "La alerta no fue encontrada o ya estaba marcada."); } } catch (System.Exception ex) { _logger.LogError(ex, "Error al marcar la alerta {IdAlerta} como leída.", idAlerta); return (false, "Error interno del servidor."); } } public async Task<(bool Exito, string? Error)> MarcarGrupoComoLeidoAsync(string tipoAlerta, int idEntidad) { var query = "UPDATE Sistema_Alertas SET Leida = 1 WHERE TipoAlerta = @TipoAlerta AND IdEntidad = @IdEntidad AND Leida = 0"; try { using (var connection = _dbConnectionFactory.CreateConnection()) { var result = await connection.ExecuteAsync(query, new { TipoAlerta = tipoAlerta, IdEntidad = idEntidad }); // No es un error si no se actualizan filas (puede que no hubiera ninguna para ese grupo) _logger.LogInformation("Marcadas como leídas {Count} alertas para Tipo: {Tipo}, EntidadID: {IdEntidad}", result, tipoAlerta, idEntidad); return (true, null); } } catch (System.Exception ex) { _logger.LogError(ex, "Error al marcar grupo de alertas como leídas. Tipo: {Tipo}, EntidadID: {IdEntidad}", tipoAlerta, idEntidad); return (false, "Error interno del servidor."); } } } }