<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Application\Query\GetPeriods\GetPeriodsHandler;
use App\Administration\Application\Query\GetPeriods\GetPeriodsQuery;
use App\Administration\Infrastructure\Api\Resource\PeriodItem;
use App\Administration\Infrastructure\Api\Resource\PeriodResource;
use App\Administration\Infrastructure\Security\PeriodVoter;
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;

/**
 * State Provider pour récupérer la configuration des périodes.
 *
 * @implements ProviderInterface<PeriodResource>
 */
final readonly class PeriodsProvider implements ProviderInterface
{
    public function __construct(
        private GetPeriodsHandler $handler,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
        private CurrentAcademicYearResolver $academicYearResolver,
    ) {
    }

    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): ?PeriodResource
    {
        if (!$this->authorizationChecker->isGranted(PeriodVoter::VIEW)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à voir les périodes.');
        }

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

        $tenantId = (string) $this->tenantContext->getCurrentTenantId();
        /** @var string $rawAcademicYearId */
        $rawAcademicYearId = $uriVariables['academicYearId'];

        $academicYearId = $this->academicYearResolver->resolve($rawAcademicYearId);
        if ($academicYearId === null) {
            throw new NotFoundHttpException('Année scolaire non trouvée.');
        }

        $result = ($this->handler)(new GetPeriodsQuery(
            tenantId: $tenantId,
            academicYearId: $academicYearId,
        ));

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

        $resource = new PeriodResource();
        $resource->academicYearId = $academicYearId;
        $resource->type = $result->type;
        $resource->periods = [];

        foreach ($result->periods as $periodDto) {
            $item = new PeriodItem();
            $item->sequence = $periodDto->sequence;
            $item->label = $periodDto->label;
            $item->startDate = $periodDto->startDate;
            $item->endDate = $periodDto->endDate;
            $item->isCurrent = $periodDto->isCurrent;
            $item->daysRemaining = $periodDto->daysRemaining;
            $item->isPast = $periodDto->isPast;
            $resource->periods[] = $item;
        }

        if ($result->currentPeriod !== null) {
            $current = new PeriodItem();
            $current->sequence = $result->currentPeriod->sequence;
            $current->label = $result->currentPeriod->label;
            $current->startDate = $result->currentPeriod->startDate;
            $current->endDate = $result->currentPeriod->endDate;
            $current->isCurrent = true;
            $current->daysRemaining = $result->currentPeriod->daysRemaining;
            $resource->currentPeriod = $current;
        }

        return $resource;
    }
}
