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

namespace GestionIntegral.Api.Data.Repositories.Comunicaciones
{
    public class LoteDeEnvioRepository : ILoteDeEnvioRepository
    {
        private readonly DbConnectionFactory _connectionFactory;
        public LoteDeEnvioRepository(DbConnectionFactory connectionFactory)
        {
            _connectionFactory = connectionFactory;
        }

        public async Task<LoteDeEnvio> CreateAsync(LoteDeEnvio lote)
        {
            const string sql = @"
                INSERT INTO dbo.com_LotesDeEnvio (FechaInicio, Periodo, Origen, Estado, IdUsuarioDisparo)
                OUTPUT INSERTED.*
                VALUES (@FechaInicio, @Periodo, @Origen, @Estado, @IdUsuarioDisparo);";
            using var connection = _connectionFactory.CreateConnection();
            return await connection.QuerySingleAsync<LoteDeEnvio>(sql, lote);
        }

        public async Task<bool> UpdateAsync(LoteDeEnvio lote)
        {
            const string sql = @"
                UPDATE dbo.com_LotesDeEnvio SET
                    FechaFin = @FechaFin,
                    Estado = @Estado,
                    TotalCorreos = @TotalCorreos,
                    TotalEnviados = @TotalEnviados,
                    TotalFallidos = @TotalFallidos
                WHERE IdLoteDeEnvio = @IdLoteDeEnvio;";
            using var connection = _connectionFactory.CreateConnection();
            var rows = await connection.ExecuteAsync(sql, lote);
            return rows == 1;
        }

        public async Task<IEnumerable<LoteDeEnvio>> GetAllAsync(int? anio, int? mes)
        {
            var sqlBuilder = new StringBuilder("SELECT * FROM dbo.com_LotesDeEnvio WHERE 1=1");
            var parameters = new DynamicParameters();

            if (anio.HasValue)
            {
                sqlBuilder.Append(" AND YEAR(FechaInicio) = @Anio");
                parameters.Add("Anio", anio.Value);
            }
            if (mes.HasValue)
            {
                sqlBuilder.Append(" AND MONTH(FechaInicio) = @Mes");
                parameters.Add("Mes", mes.Value);
            }

            sqlBuilder.Append(" ORDER BY FechaInicio DESC;");

            using var connection = _connectionFactory.CreateConnection();
            return await connection.QueryAsync<LoteDeEnvio>(sqlBuilder.ToString(), parameters);
        }

        public async Task<LoteDeEnvio?> GetByIdAsync(int id)
        {
            const string sql = "SELECT * FROM dbo.com_LotesDeEnvio WHERE IdLoteDeEnvio = @Id;";
            using var connection = _connectionFactory.CreateConnection();
            return await connection.QuerySingleOrDefaultAsync<LoteDeEnvio>(sql, new { Id = id });
        }
    }
}