<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Domain\Model\SchoolCalendar\SchoolCalendar;
use App\Administration\Domain\Model\SchoolCalendar\SchoolCalendarRepository;
use App\Administration\Domain\Model\SchoolClass\AcademicYearId;
use App\Administration\Domain\Model\SchoolClass\ClassId;
use App\Administration\Infrastructure\Service\CurrentAcademicYearResolver;
use App\Scolarite\Application\Service\ScheduleResolver;
use App\Scolarite\Infrastructure\Api\Resource\ResolvedScheduleSlotResource;
use App\Scolarite\Infrastructure\Security\ScheduleSlotVoter;
use App\Shared\Domain\Tenant\TenantId;
use App\Shared\Infrastructure\Tenant\TenantContext;

use function array_map;

use DateTimeImmutable;
use Override;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * Provider pour l'emploi du temps résolu d'une semaine.
 *
 * @implements ProviderInterface<ResolvedScheduleSlotResource>
 */
final readonly class ResolvedScheduleWeekProvider implements ProviderInterface
{
    public function __construct(
        private ScheduleResolver $scheduleResolver,
        private SchoolCalendarRepository $calendarRepository,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
        private CurrentAcademicYearResolver $academicYearResolver,
    ) {
    }

    /** @return array<ResolvedScheduleSlotResource> */
    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): array
    {
        if (!$this->authorizationChecker->isGranted(ScheduleSlotVoter::VIEW)) {
            throw new AccessDeniedHttpException("Vous n'êtes pas autorisé à consulter l'emploi du temps.");
        }

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

        /** @var array<string, string> $filters */
        $filters = $context['filters'] ?? [];

        if (!isset($filters['classId'])) {
            throw new BadRequestHttpException('Le paramètre classId est requis.');
        }

        /** @var string $dateParam */
        $dateParam = $uriVariables['date'] ?? '';
        $weekStart = new DateTimeImmutable($dateParam);

        $tenantId = TenantId::fromString((string) $this->tenantContext->getCurrentTenantId());
        $classId = ClassId::fromString((string) $filters['classId']);

        $calendar = $this->loadCalendar($tenantId);

        // TODO: cache-aside par classId+weekStart si la perf le nécessite
        $resolved = $this->scheduleResolver->resolveForWeek(
            $classId,
            $weekStart,
            $tenantId,
            $calendar,
        );

        return array_map(ResolvedScheduleSlotResource::fromDomain(...), $resolved);
    }

    private function loadCalendar(TenantId $tenantId): SchoolCalendar
    {
        $academicYearId = $this->academicYearResolver->resolve('current');

        if ($academicYearId === null) {
            return SchoolCalendar::initialiser($tenantId, AcademicYearId::generate());
        }

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

        return $calendar ?? SchoolCalendar::initialiser($tenantId, AcademicYearId::generate());
    }
}
