using Dapper;
using GestionIntegral.Api.Models.Suscripciones;

namespace GestionIntegral.Api.Data.Repositories.Suscripciones
{
    public class FormaPagoRepository : IFormaPagoRepository
    {
        private readonly DbConnectionFactory _connectionFactory;
        private readonly ILogger<FormaPagoRepository> _logger;

        public FormaPagoRepository(DbConnectionFactory connectionFactory, ILogger<FormaPagoRepository> logger)
        {
            _connectionFactory = connectionFactory;
            _logger = logger;
        }

        public async Task<IEnumerable<FormaPago>> GetAllAsync()
        {
            const string sql = @"
                SELECT IdFormaPago, Nombre, RequiereCBU, Activo 
                FROM dbo.susc_FormasDePago 
                WHERE Activo = 1 
                ORDER BY Nombre;";
            try
            {
                using var connection = _connectionFactory.CreateConnection();
                return await connection.QueryAsync<FormaPago>(sql);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error al obtener todas las Formas de Pago activas.");
                return Enumerable.Empty<FormaPago>();
            }
        }

        public async Task<FormaPago?> GetByIdAsync(int id)
        {
            const string sql = @"
                SELECT IdFormaPago, Nombre, RequiereCBU, Activo 
                FROM dbo.susc_FormasDePago 
                WHERE IdFormaPago = @Id;";
            try
            {
                using var connection = _connectionFactory.CreateConnection();
                return await connection.QuerySingleOrDefaultAsync<FormaPago>(sql, new { Id = id });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error al obtener Forma de Pago por ID: {IdFormaPago}", id);
                return null;
            }
        }
    }
}