<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\UpdatePeriod\UpdatePeriodCommand;
use App\Administration\Application\Command\UpdatePeriod\UpdatePeriodHandler;
use App\Administration\Domain\Exception\InvalidPeriodDatesException;
use App\Administration\Domain\Exception\PeriodeAvecNotesException;
use App\Administration\Domain\Exception\PeriodeNonTrouveeException;
use App\Administration\Domain\Exception\PeriodesNonConfigureesException;
use App\Administration\Domain\Exception\PeriodsCoverageGapException;
use App\Administration\Domain\Exception\PeriodsOverlapException;
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 DateMalformedStringException;
use Override;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
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 modifier les dates d'une période.
 *
 * @implements ProcessorInterface<PeriodResource, PeriodResource>
 */
final readonly class UpdatePeriodProcessor implements ProcessorInterface
{
    public function __construct(
        private UpdatePeriodHandler $handler,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
        private CurrentAcademicYearResolver $academicYearResolver,
    ) {
    }

    /**
     * @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é à modifier 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.');
        }

        /** @var int|string $sequence */
        $sequence = $uriVariables['sequence'];

        $startDate = $data->startDate;
        $endDate = $data->endDate;

        if ($startDate === null || $startDate === '' || $endDate === null || $endDate === '') {
            throw new BadRequestHttpException('Les dates de début et de fin sont obligatoires.');
        }

        try {
            $command = new UpdatePeriodCommand(
                tenantId: $tenantId,
                academicYearId: $academicYearId,
                sequence: (int) $sequence,
                startDate: $startDate,
                endDate: $endDate,
                confirmImpact: $data->confirmImpact ?? false,
            );

            $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 (PeriodesNonConfigureesException|PeriodeNonTrouveeException $e) {
            throw new NotFoundHttpException($e->getMessage());
        } catch (PeriodeAvecNotesException $e) {
            throw new ConflictHttpException($e->getMessage());
        } catch (InvalidPeriodDatesException|PeriodsOverlapException|PeriodsCoverageGapException $e) {
            throw new BadRequestHttpException($e->getMessage());
        } catch (DateMalformedStringException $e) {
            throw new BadRequestHttpException('Format de date invalide : ' . $e->getMessage());
        }
    }
}
