<?php

declare(strict_types=1);

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

use Gls\GlsPoland\PrestaShop\Checkout\CheckoutResolverInterface;
use Gls\GlsPoland\PrestaShop\Checkout\Event\ValidateStepCompleteEvent;
use Gls\GlsPoland\PrestaShop\Hook\HookInterface;
use Symfony\Component\HttpFoundation\Request;

final class ActionValidateStepComplete implements HookInterface
{
    public const HOOK_NAME = 'actionValidateStepComplete';

    private $checkoutResolver;

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

    /**
     * @param array{step_name: string, request_params: array, completed: bool, cart: \Cart, request: Request} $parameters
     */
    public function execute(array $parameters): void
    {
        if ('delivery' !== ($parameters['step_name'] ?? null)) {
            return;
        }

        $cart = $parameters['cart'] ?? null;
        $request = $parameters['request'] ?? null;

        if (!$cart instanceof \Cart || !$request instanceof Request) {
            return;
        }

        if (!is_array($requestParameters = $parameters['request_params'] ?? null)) {
            return;
        }

        $parameters['completed'] = $this->checkoutResolver
            ->dispatch(new ValidateStepCompleteEvent($cart, $request, $requestParameters))
            ->isComplete();
    }
}
