<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\ConfigureCalendar\ConfigureCalendarCommand;
use App\Administration\Application\Command\ConfigureCalendar\ConfigureCalendarHandler;
use App\Administration\Infrastructure\Api\Resource\CalendarResource;
use App\Administration\Infrastructure\Security\CalendarVoter;
use App\Administration\Infrastructure\Service\CurrentAcademicYearResolver;
use App\Shared\Infrastructure\Tenant\TenantContext;
use InvalidArgumentException;
use Override;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use ValueError;

/**
 * @implements ProcessorInterface<CalendarResource, CalendarResource>
 */
final readonly class ConfigureCalendarProcessor implements ProcessorInterface
{
    public function __construct(
        private ConfigureCalendarHandler $handler,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
        private CurrentAcademicYearResolver $academicYearResolver,
        private MessageBusInterface $eventBus,
    ) {
    }

    #[Override]
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): CalendarResource
    {
        if (!$this->authorizationChecker->isGranted(CalendarVoter::CONFIGURE)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à configurer le calendrier.');
        }

        if (!$this->tenantContext->hasTenant()) {
            throw new UnauthorizedHttpException('Bearer', 'Tenant non défini.');
        }

        /** @var string $rawAcademicYearId */
        $rawAcademicYearId = $uriVariables['academicYearId'];
        $academicYearId = $this->academicYearResolver->resolve($rawAcademicYearId);

        if ($academicYearId === null) {
            throw new NotFoundHttpException('Année scolaire non trouvée.');
        }

        $tenantId = (string) $this->tenantContext->getCurrentTenantId();

        $startYear = $this->academicYearResolver->resolveStartYear($rawAcademicYearId);

        if ($startYear === null) {
            throw new BadRequestHttpException(
                'Impossible de déterminer l\'année scolaire pour l\'identifiant fourni. '
                . 'Utilisez "previous", "current" ou "next".',
            );
        }

        $academicYear = $startYear . '-' . ($startYear + 1);

        try {
            $command = new ConfigureCalendarCommand(
                tenantId: $tenantId,
                academicYearId: $academicYearId,
                zone: $data->zone ?? $data->importZone ?? throw new BadRequestHttpException('La zone scolaire est requise.'),
                academicYear: $academicYear,
            );

            $calendar = ($this->handler)($command);

            foreach ($calendar->pullDomainEvents() as $event) {
                $this->eventBus->dispatch($event);
            }

            return CalendarResource::fromCalendar($calendar, $academicYearId);
        } catch (InvalidArgumentException|ValueError $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
    }
}
