<?php

/*
 * This file is part of the VitiCore 2.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\ValueResolver;

use CpCreation\VitiCore\Behavior\HasPayment;
use CpCreation\VitiCore\Cart\Model\Cart;
use CpCreation\VitiCore\Cart\Repository\CartRepository;
use CpCreation\VitiCore\Payment\Model\Payment;
use CpCreation\VitiCore\Payment\Repository\PaymentRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Attribute\AsTargetedValueResolver;
use Symfony\Component\HttpKernel\Controller\ValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;

#[AsTargetedValueResolver('haspayment_resolver')]
final readonly class HasPaymentValueResolver implements ValueResolverInterface
{
    public function __construct(
        private CartRepository $cartRepository,
        private PaymentRepository $paymentRepository,
    ) {
    }

    public function resolve(Request $request, ArgumentMetadata $argument): iterable
    {
        // équivalent à supports(): uniquement si l'argument est typé HasPayment (exactement)
        if (HasPayment::class !== $argument->getType()) {
            return [];
        }

        $id = $request->attributes->get('id');
        if (!\is_scalar($id) || '' === $id || null === $id) {
            // Dans ton ParamConverter: return false
            return [];
        }

        $id = (string) $id;

        $cart = $this->cartRepository->find($id);
        if ($cart instanceof Cart) {
            return [$cart];
        }

        $payment = $this->paymentRepository->find($id);
        if ($payment instanceof Payment) {
            return [$payment];
        }

        $class = $request->get('class');

        throw new \RuntimeException(\sprintf('Expected an instance of %s or %s. Got: %s', Cart::class, Payment::class, (string) $class));
    }
}
