<?php

namespace App\Services\Payment;

use App\Contracts\PaymentGatewayInterface;
use App\Services\Payment\Providers\FlutterwaveProvider;
use Illuminate\Support\Facades\Log;

class PaymentGatewayManager
{
    protected array $providers = [];
    protected string $defaultProvider = 'flutterwave';

    public function __construct()
    {
        $this->registerProviders();
    }

    /**
     * Enregistrer les providers disponibles
     */
    protected function registerProviders(): void
    {
        // Flutterwave (actif par défaut)
        $this->register('flutterwave', new FlutterwaveProvider());

        // Les autres providers (Stripe, PayPal, etc.) seront ajoutés ici à l'avenir
        // $this->register('stripe', new StripeProvider());
        // $this->register('paypal', new PayPalProvider());
    }

    /**
     * Enregistrer un provider personnalisé
     */
    public function register(string $name, PaymentGatewayInterface $provider): self
    {
        $this->providers[$name] = $provider;
        Log::info("Payment provider registered: $name");
        return $this;
    }

    /**
     * Obtenir un provider spécifique
     */
    public function provider(string $name = null): PaymentGatewayInterface
    {
        $name = $name ?? $this->defaultProvider;

        if (!isset($this->providers[$name])) {
            throw new \Exception("Payment provider '$name' not found. Available: " . implode(', ', array_keys($this->providers)));
        }

        return $this->providers[$name];
    }

    /**
     * Utiliser le provider par défaut
     */
    public function __call(string $method, array $arguments)
    {
        return $this->provider()->{$method}(...$arguments);
    }

    /**
     * Lister tous les providers disponibles
     */
    public function available(): array
    {
        return array_keys($this->providers);
    }

    /**
     * Définir le provider par défaut
     */
    public function setDefault(string $name): self
    {
        if (!isset($this->providers[$name])) {
            throw new \Exception("Payment provider '$name' not found");
        }
        $this->defaultProvider = $name;
        return $this;
    }
}
