<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\AddPedagogicalDay\AddPedagogicalDayCommand;
use App\Administration\Application\Command\AddPedagogicalDay\AddPedagogicalDayHandler;
use App\Administration\Domain\Exception\CalendrierDatesInvalidesException;
use App\Administration\Domain\Exception\CalendrierLabelInvalideException;
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;

/**
 * @implements ProcessorInterface<CalendarResource, CalendarResource>
 */
final readonly class AddPedagogicalDayProcessor implements ProcessorInterface
{
    public function __construct(
        private AddPedagogicalDayHandler $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é à ajouter une journée pédagogique.');
        }

        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.');
        }

        if ($data->date === null || $data->label === null) {
            throw new BadRequestHttpException('La date et le libellé sont requis.');
        }

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

        try {
            $command = new AddPedagogicalDayCommand(
                tenantId: $tenantId,
                academicYearId: $academicYearId,
                date: $data->date,
                label: $data->label,
                description: $data->description,
            );

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

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

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