<?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\UpdateRecurringSlot\UpdateRecurringSlotCommand;
use App\Scolarite\Application\Command\UpdateRecurringSlot\UpdateRecurringSlotHandler;
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\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;
use ValueError;

/**
 * @implements ProcessorInterface<ScheduleOccurrenceResource, ScheduleOccurrenceResource>
 */
final readonly class ModifyOccurrenceProcessor implements ProcessorInterface
{
    public function __construct(
        private UpdateRecurringSlotHandler $handler,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
        private TokenStorageInterface $tokenStorage,
    ) {
    }

    /**
     * @param ScheduleOccurrenceResource $data
     */
    #[Override]
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): ScheduleOccurrenceResource
    {
        if (!$this->authorizationChecker->isGranted(ScheduleSlotVoter::EDIT)) {
            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() : '';

        try {
            $command = new UpdateRecurringSlotCommand(
                tenantId: (string) $this->tenantContext->getCurrentTenantId(),
                slotId: $slotId,
                occurrenceDate: $date,
                scope: $data->scope ?? 'this_occurrence',
                classId: $data->classId ?? '',
                subjectId: $data->subjectId ?? '',
                teacherId: $data->teacherId ?? '',
                dayOfWeek: $data->dayOfWeek ?? 1,
                startTime: $data->startTime ?? '',
                endTime: $data->endTime ?? '',
                room: $data->room,
                updatedBy: $userId,
            );

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

            $resource = new ScheduleOccurrenceResource();
            $resource->id = $slotId . '_' . $date;
            $resource->slotId = $slotId;
            $resource->date = $date;
            $resource->scope = $data->scope;
            $resource->type = $result['exception'] !== null ? 'modified' : 'recurring_updated';

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