<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\Controller\Front\Checkout;

use InPost\International\Checkout\Form\DeliveryOptionsFormFactoryInterface;
use PrestaShop\PrestaShop\Core\CommandBus\CommandBusInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;

if (!defined('_PS_VERSION_')) {
    exit;
}

final class UpdateDeliveryOptionsController
{
    /**
     * @var \Context
     */
    private $context;

    /**
     * @var DeliveryOptionsFormFactoryInterface
     */
    private $formFactory;

    /**
     * @var CommandBusInterface
     */
    private $commandBus;

    public function __construct(\Context $context, DeliveryOptionsFormFactoryInterface $formFactory, CommandBusInterface $commandBus)
    {
        $this->context = $context;
        $this->formFactory = $formFactory;
        $this->commandBus = $commandBus;
    }

    public function __invoke(Request $request): Response
    {
        $cart = $this->context->cart;

        if (!$cart->hasProducts()) {
            throw new ConflictHttpException('Cart is empty.');
        }

        $deliveryOption = $cart->getDeliveryOption();

        if (null === $form = $this->formFactory->getForDeliveryOption($cart, $deliveryOption)) {
            throw new BadRequestHttpException('The selected delivery option in not associated with an InPost carrier.');
        }

        $form->handleRequest($request);

        if (!$form->isSubmitted()) {
            throw new BadRequestHttpException(sprintf('Malformed request: "%s" is missing.', $form->getName()));
        }

        if ($form->isValid()) {
            $this->commandBus->handle($form->getData());

            return new Response('', Response::HTTP_NO_CONTENT);
        }

        $errors = $this->getFormErrors($form);

        return new JsonResponse($errors, Response::HTTP_UNPROCESSABLE_ENTITY);
    }

    private function getFormErrors(FormInterface $form): array
    {
        $errors = [];

        foreach ($form->getErrors(true) as $error) {
            $name = self::getOriginName($error) ?? $form->getName();
            $errors[$name] = $error->getMessage();
        }

        return $errors;
    }

    private static function getOriginName(FormError $error): ?string
    {
        if (null === $form = $error->getOrigin()) {
            return null;
        }

        $name = $form->getName();

        while (null !== $form = $form->getParent()) {
            $name = sprintf('%s[%s]', $form->getName(), $name);
        }

        return $name;
    }
}
