<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Domain\Model\SchoolCalendar\SchoolCalendarRepository;
use App\Administration\Domain\Model\SchoolClass\AcademicYearId;
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 Override;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * @implements ProviderInterface<CalendarResource>
 */
final readonly class CalendarProvider implements ProviderInterface
{
    public function __construct(
        private SchoolCalendarRepository $calendarRepository,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
        private CurrentAcademicYearResolver $academicYearResolver,
    ) {
    }

    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): ?CalendarResource
    {
        if (!$this->authorizationChecker->isGranted(CalendarVoter::VIEW)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à voir 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 = $this->tenantContext->getCurrentTenantId();

        $calendar = $this->calendarRepository->findByTenantAndYear(
            $tenantId,
            AcademicYearId::fromString($academicYearId),
        );

        if ($calendar === null) {
            return null;
        }

        return CalendarResource::fromCalendar($calendar, $academicYearId);
    }
}
