<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\UpdateBranding\UpdateBrandingCommand;
use App\Administration\Application\Command\UpdateBranding\UpdateBrandingHandler;
use App\Administration\Domain\Exception\BrandColorInvalideException;
use App\Administration\Domain\Exception\ContrasteInsuffisantException;
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\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 modifier les couleurs du branding.
 *
 * @implements ProcessorInterface<SchoolBrandingResource, SchoolBrandingResource>
 */
final readonly class UpdateBrandingColorsProcessor implements ProcessorInterface
{
    public function __construct(
        private UpdateBrandingHandler $handler,
        private TenantContext $tenantContext,
        private MessageBusInterface $eventBus,
        private AuthorizationCheckerInterface $authorizationChecker,
        private SchoolIdResolver $schoolIdResolver,
    ) {
    }

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

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

        try {
            $command = new UpdateBrandingCommand(
                tenantId: $tenantId,
                schoolId: $schoolId,
                primaryColor: $data->primaryColor,
                secondaryColor: $data->secondaryColor,
                accentColor: $data->accentColor,
            );

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

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

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