<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\UploadLogo\UploadLogoCommand;
use App\Administration\Application\Command\UploadLogo\UploadLogoHandler;
use App\Administration\Domain\Exception\LogoFormatInvalideException;
use App\Administration\Domain\Exception\LogoTraitementImpossibleException;
use App\Administration\Domain\Exception\LogoTropGrosException;
use App\Administration\Infrastructure\Api\Resource\SchoolBrandingResource;
use App\Administration\Infrastructure\School\SchoolIdResolver;
use App\Administration\Infrastructure\Security\SchoolBrandingVoter;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * Processor API Platform pour l'upload du logo (POST /school/branding/logo).
 *
 * @implements ProcessorInterface<SchoolBrandingResource, SchoolBrandingResource>
 */
final readonly class UploadLogoProcessor implements ProcessorInterface
{
    public function __construct(
        private UploadLogoHandler $handler,
        private TenantContext $tenantContext,
        private MessageBusInterface $eventBus,
        private AuthorizationCheckerInterface $authorizationChecker,
        private SchoolIdResolver $schoolIdResolver,
        private RequestStack $requestStack,
    ) {
    }

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

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

        $request = $this->requestStack->getCurrentRequest();
        $file = $request?->files->get('file');

        if (!$file instanceof UploadedFile) {
            throw new BadRequestHttpException('Le fichier du logo est requis.');
        }

        $tenantId = (string) $this->tenantContext->getCurrentTenantId();
        $schoolId = $this->schoolIdResolver->resolveForTenant($tenantId);

        try {
            $command = new UploadLogoCommand(
                tenantId: $tenantId,
                schoolId: $schoolId,
                file: $file,
            );

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

            foreach ($branding->pullDomainEvents() as $event) {
                $this->eventBus->dispatch($event);
            }

            return SchoolBrandingResource::fromDomain($branding);
        } catch (LogoTropGrosException|LogoFormatInvalideException|LogoTraitementImpossibleException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
    }
}
