<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Infrastructure\Security\SecurityUser;
use App\Scolarite\Application\Command\CreateScheduleException\CreateScheduleExceptionCommand;
use App\Scolarite\Application\Command\CreateScheduleException\CreateScheduleExceptionHandler;
use App\Scolarite\Application\Command\TruncateSlotRecurrence\TruncateSlotRecurrenceCommand;
use App\Scolarite\Application\Command\TruncateSlotRecurrence\TruncateSlotRecurrenceHandler;
use App\Scolarite\Domain\Exception\DateExceptionInvalideException;
use App\Scolarite\Domain\Exception\ScheduleSlotNotFoundException;
use App\Scolarite\Infrastructure\Api\Resource\ScheduleOccurrenceResource;
use App\Scolarite\Infrastructure\Security\ScheduleSlotVoter;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
use Symfony\Component\HttpFoundation\RequestStack;
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\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * @implements ProcessorInterface<ScheduleOccurrenceResource, ScheduleOccurrenceResource>
 */
final readonly class CancelOccurrenceProcessor implements ProcessorInterface
{
    public function __construct(
        private CreateScheduleExceptionHandler $cancelHandler,
        private TruncateSlotRecurrenceHandler $truncateHandler,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
        private TokenStorageInterface $tokenStorage,
        private RequestStack $requestStack,
    ) {
    }

    /**
     * @param ScheduleOccurrenceResource|null $data
     */
    #[Override]
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): ScheduleOccurrenceResource
    {
        if (!$this->authorizationChecker->isGranted(ScheduleSlotVoter::DELETE)) {
            throw new AccessDeniedHttpException("Vous n'êtes pas autorisé à modifier l'emploi du temps.");
        }

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

        /** @var string $slotId */
        $slotId = $uriVariables['id'] ?? '';
        /** @var string $date */
        $date = $uriVariables['date'] ?? '';

        $user = $this->tokenStorage->getToken()?->getUser();
        $userId = $user instanceof SecurityUser ? $user->userId() : '';
        $tenantId = (string) $this->tenantContext->getCurrentTenantId();

        $scope = $this->requestStack->getCurrentRequest()?->query->getString('scope', 'this_occurrence');

        try {
            if ($scope === 'all_future') {
                ($this->truncateHandler)(new TruncateSlotRecurrenceCommand(
                    tenantId: $tenantId,
                    slotId: $slotId,
                    fromDate: $date,
                    updatedBy: $userId,
                ));

                $type = 'truncated';
            } else {
                ($this->cancelHandler)(new CreateScheduleExceptionCommand(
                    tenantId: $tenantId,
                    slotId: $slotId,
                    exceptionDate: $date,
                    type: 'cancelled',
                    createdBy: $userId,
                    reason: $data?->reason,
                ));

                $type = 'cancelled';
            }

            $resource = new ScheduleOccurrenceResource();
            $resource->id = $slotId . '_' . $date;
            $resource->slotId = $slotId;
            $resource->date = $date;
            $resource->type = $type;

            return $resource;
        } catch (ScheduleSlotNotFoundException $e) {
            throw new NotFoundHttpException($e->getMessage());
        } catch (DateExceptionInvalideException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
    }
}
