<?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;

use PrestaShop\PrestaShop\Core\CommandBus\CommandBusInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController as BaseController;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\Translation\TranslatorInterface;

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

abstract class AbstractController extends BaseController
{
    /**
     * @var bool
     */
    protected $debug;

    public function __construct(bool $debug = false)
    {
        $this->debug = $debug;
    }

    public static function getSubscribedServices(): array
    {
        return parent::getSubscribedServices() + [
            CommandBusInterface::class,
            'translator' => TranslatorInterface::class,
            'logger' => '?' . LoggerInterface::class,
        ];
    }

    /**
     * Returns true if the service id is defined.
     *
     * @param string $id
     */
    final protected function has($id): bool
    {
        return $this->container->has($id);
    }

    /**
     * Gets a container service by its id.
     *
     * @param string $id
     */
    final protected function get($id): object
    {
        return $this->container->get($id);
    }

    final protected function trans(string $id, array $parameters = [], string $domain = null, string $locale = null): string
    {
        return $this->get('translator')->trans($id, $parameters, $domain, $locale);
    }

    /**
     * @return mixed
     */
    final protected function handle(object $command)
    {
        return $this->get(CommandBusInterface::class)->handle($command);
    }

    protected function getLogger(): LoggerInterface
    {
        return $this->has('logger') ? $this->get('logger') : new NullLogger();
    }

    protected function createResponseForForm(FormInterface $form): Response
    {
        $status = $form->isSubmitted() && !$form->isValid() ? Response::HTTP_UNPROCESSABLE_ENTITY : Response::HTTP_OK;

        return new Response(null, $status);
    }
}
