<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\Payments\Provider;

use Ferienpass\CoreBundle\Entity\Payment;
use Symfony\Component\DependencyInjection\Attribute\AutowireIterator;
use Symfony\Component\HttpFoundation\Request;

class PaymentProviderChain implements PaymentProviderInterface
{
    /**
     * @param iterable<PaymentProviderInterface> $providers
     */
    public function __construct(#[AutowireIterator('ferienpass.payment_provider')] private readonly iterable $providers)
    {
    }

    public function dispatchPayment(Payment $payment): string
    {
        return $this->getProvider()->dispatchPayment($payment);
    }

    public function interpretRedirect(Request $request): int
    {
        return $this->getProvider()->interpretRedirect($request);
    }

    public function isConfigured(): bool
    {
        foreach ($this->providers as $provider) {
            if ($provider instanceof self) {
                continue;
            }

            if ($provider->isConfigured()) {
                return true;
            }
        }

        return false;
    }

    private function getProvider(): PaymentProviderInterface
    {
        foreach ($this->providers as $provider) {
            if ($provider instanceof self) {
                continue;
            }

            if ($provider->isConfigured()) {
                return $provider;
            }
        }

        foreach ($this->providers as $provider) {
            if ($provider instanceof NoOpPaymentProvider) {
                return $provider;
            }
        }

        throw new \RuntimeException('No payment provider configured and no fallback available.');
    }
}
