using Dapper;
using GestionIntegral.Api.Models.Comunicaciones;

namespace GestionIntegral.Api.Data.Repositories.Comunicaciones
{
  public class EmailLogRepository : IEmailLogRepository
  {
    private readonly DbConnectionFactory _connectionFactory;
    private readonly ILogger<EmailLogRepository> _logger;
    public EmailLogRepository(DbConnectionFactory connectionFactory, ILogger<EmailLogRepository> logger)
    {
      _connectionFactory = connectionFactory;
      _logger = logger;
    }

    public async Task CreateAsync(EmailLog log)
    {
      const string sql = @"
        INSERT INTO dbo.com_EmailLogs 
            (FechaEnvio, DestinatarioEmail, Asunto, Estado, Error, IdUsuarioDisparo, Origen, ReferenciaId, IdLoteDeEnvio) 
        VALUES 
            (@FechaEnvio, @DestinatarioEmail, @Asunto, @Estado, @Error, @IdUsuarioDisparo, @Origen, @ReferenciaId, @IdLoteDeEnvio);";

      using var connection = _connectionFactory.CreateConnection();
      await connection.ExecuteAsync(sql, log);
    }

    public async Task<IEnumerable<EmailLog>> GetByReferenceAsync(string referenciaId)
    {
      const string sql = @"
            SELECT * FROM dbo.com_EmailLogs
            WHERE ReferenciaId = @ReferenciaId
            ORDER BY FechaEnvio DESC;";
      try
      {
        using var connection = _connectionFactory.CreateConnection();
        return await connection.QueryAsync<EmailLog>(sql, new { ReferenciaId = referenciaId });
      }
      catch (System.Exception ex)
      {
        _logger.LogError(ex, "Error al obtener logs de email por ReferenciaId: {ReferenciaId}", referenciaId);
        return Enumerable.Empty<EmailLog>();
      }
    }

    public async Task<IEnumerable<EmailLog>> GetByLoteIdAsync(int idLoteDeEnvio)
    {
      // Ordenamos por Estado descendente para que los 'Fallidos' aparezcan primero
      const string sql = @"
            SELECT * FROM dbo.com_EmailLogs
            WHERE IdLoteDeEnvio = @IdLoteDeEnvio
            ORDER BY Estado DESC, FechaEnvio DESC;";
      try
      {
        using var connection = _connectionFactory.CreateConnection();
        return await connection.QueryAsync<EmailLog>(sql, new { IdLoteDeEnvio = idLoteDeEnvio });
      }
      catch (Exception ex)
      {
        _logger.LogError(ex, "Error al obtener logs de email por IdLoteDeEnvio: {IdLoteDeEnvio}", idLoteDeEnvio);
        return Enumerable.Empty<EmailLog>();
      }
    }
  }
}