<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\Hook\Front\Checkout;

use Gls\GlsPoland\PrestaShop\Checkout\CheckoutResolverInterface;
use Gls\GlsPoland\PrestaShop\Helper\CarrierFinder;
use Gls\GlsPoland\PrestaShop\Hook\HookInterface;
use Symfony\Component\HttpFoundation\Request;

final class DisplayCarrierExtraContent implements HookInterface
{
    public const HOOK_NAME = 'displayCarrierExtraContent';

    private $carrierFinder;
    private $checkoutResolver;

    public function __construct(CarrierFinder $carrierFinder, CheckoutResolverInterface $checkoutResolver)
    {
        $this->carrierFinder = $carrierFinder;
        $this->checkoutResolver = $checkoutResolver;
    }

    /**
     * @param array{carrier: array{id: int}, cart: \Cart, request: Request} $parameters
     */
    public function execute(array $parameters): string
    {
        $carrierId = isset($parameters['carrier']['id']) ? (int) $parameters['carrier']['id'] : null;
        $cart = $parameters['cart'] ?? null;

        if (0 >= $carrierId || !$cart instanceof \Cart) {
            return '';
        }

        if (null === $checkout = $this->checkoutResolver->resolve($parameters['request'] ?? null)) {
            return '';
        }

        if (null === $carrier = $this->carrierFinder->findOneByCarrierId($carrierId)) {
            return '';
        }

        return $checkout->renderDeliveryOptionsForm($carrier, $cart, $carrierId);
    }
}
