using Tiku.Application.Commerce;

namespace Tiku.Infrastructure.Commerce;

internal sealed class PaymentProviderGateway(
    IEnumerable<IPaymentProvider> providers,
    IPaymentProviderConfigService configService) : IPaymentProviderGateway
{
    public async Task<CreatePaymentProviderResult> CreatePaymentAsync(
        string provider,
        CreatePaymentProviderRequest request,
        CancellationToken cancellationToken = default)
    {
        var resolvedProvider = ResolveProvider(provider);
        var account = await configService.GetActiveAccountAsync(
            request.TenantId,
            resolvedProvider.Provider,
            cancellationToken);

        return await resolvedProvider.CreatePaymentAsync(account, request, cancellationToken);
    }

    public async Task<PaymentNotificationResult> ParsePaymentNotificationAsync(
        string provider,
        PaymentNotificationRequest request,
        CancellationToken cancellationToken = default)
    {
        var resolvedProvider = ResolveProvider(provider);
        var account = await configService.GetActiveAccountAsync(
            request.TenantId,
            resolvedProvider.Provider,
            cancellationToken);

        return await resolvedProvider.ParsePaymentNotificationAsync(account, request, cancellationToken);
    }

    private IPaymentProvider ResolveProvider(string provider)
    {
        var normalized = provider.Trim().ToLowerInvariant().Replace("-", "_", StringComparison.Ordinal);
        return providers.FirstOrDefault(item => item.Provider == normalized)
               ?? throw new PaymentProviderException(
                   "Payment provider is not supported.",
                   "payment_provider_not_supported");
    }
}