<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Infrastructure\Service\CurrentAcademicYearResolver;
use App\Scolarite\Application\Query\GetBlockedDates\GetBlockedDatesHandler;
use App\Scolarite\Application\Query\GetBlockedDates\GetBlockedDatesQuery;
use App\Scolarite\Infrastructure\Api\Resource\BlockedDateResource;
use App\Scolarite\Infrastructure\Security\ScheduleSlotVoter;
use App\Shared\Infrastructure\Tenant\TenantContext;

use function array_map;

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;

/**
 * State Provider pour récupérer les dates bloquées (jours fériés, vacances, etc.).
 *
 * @implements ProviderInterface<BlockedDateResource>
 */
final readonly class BlockedDateCollectionProvider implements ProviderInterface
{
    public function __construct(
        private GetBlockedDatesHandler $handler,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
        private CurrentAcademicYearResolver $academicYearResolver,
    ) {
    }

    /** @return array<BlockedDateResource> */
    #[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 les dates bloquées.");
        }

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

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

        if (!isset($filters['startDate'], $filters['endDate'])) {
            throw new BadRequestHttpException('Les paramètres startDate et endDate sont requis.');
        }

        $tenantId = (string) $this->tenantContext->getCurrentTenantId();
        $academicYearId = $this->academicYearResolver->resolve('current');

        if ($academicYearId === null) {
            return [];
        }

        $query = new GetBlockedDatesQuery(
            tenantId: $tenantId,
            academicYearId: $academicYearId,
            startDate: (string) $filters['startDate'],
            endDate: (string) $filters['endDate'],
        );

        $dtos = ($this->handler)($query);

        return array_map(BlockedDateResource::fromDto(...), $dtos);
    }
}
