<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\ConfigurePeriods\ConfigurePeriodsCommand;
use App\Administration\Application\Command\ConfigurePeriods\ConfigurePeriodsHandler;
use App\Administration\Domain\Exception\PeriodesDejaConfigureesException;
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\Domain\Clock;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * Processor API Platform pour configurer les périodes d'une année scolaire.
 *
 * @implements ProcessorInterface<PeriodResource, PeriodResource>
 */
final readonly class ConfigurePeriodsProcessor implements ProcessorInterface
{
    public function __construct(
        private ConfigurePeriodsHandler $handler,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
        private CurrentAcademicYearResolver $academicYearResolver,
        private Clock $clock,
    ) {
    }

    /**
     * @param PeriodResource $data
     */
    #[Override]
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): PeriodResource
    {
        if (!$this->authorizationChecker->isGranted(PeriodVoter::CONFIGURE)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à configurer 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.');
        }

        try {
            $startYear = $data->startYear
                ?? $this->academicYearResolver->resolveStartYear($rawAcademicYearId)
                ?? (int) $this->clock->now()->format('Y');

            $command = new ConfigurePeriodsCommand(
                tenantId: $tenantId,
                academicYearId: $academicYearId,
                periodType: $data->periodType ?? 'trimester',
                startYear: $startYear,
            );

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

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

            foreach ($config->periods as $period) {
                $item = new PeriodItem();
                $item->sequence = $period->sequence;
                $item->label = $period->label;
                $item->startDate = $period->startDate->format('Y-m-d');
                $item->endDate = $period->endDate->format('Y-m-d');
                $resource->periods[] = $item;
            }

            return $resource;
        } catch (PeriodesDejaConfigureesException $e) {
            throw new ConflictHttpException($e->getMessage());
        }
    }
}
