<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Domain\Model\SchoolBranding\SchoolBranding;
use App\Administration\Domain\Model\SchoolClass\SchoolId;
use App\Administration\Domain\Repository\SchoolBrandingRepository;
use App\Administration\Infrastructure\Api\Resource\SchoolBrandingResource;
use App\Administration\Infrastructure\School\SchoolIdResolver;
use App\Administration\Infrastructure\Security\SchoolBrandingVoter;
use App\Shared\Domain\Clock;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * State Provider pour récupérer la configuration branding de l'établissement.
 *
 * @implements ProviderInterface<SchoolBrandingResource>
 */
final readonly class SchoolBrandingProvider implements ProviderInterface
{
    public function __construct(
        private SchoolBrandingRepository $brandingRepository,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
        private SchoolIdResolver $schoolIdResolver,
        private Clock $clock,
    ) {
    }

    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): SchoolBrandingResource
    {
        if (!$this->authorizationChecker->isGranted(SchoolBrandingVoter::VIEW)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à voir la configuration du branding.');
        }

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

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

        $branding = $this->brandingRepository->findBySchoolId($schoolId, $tenantId);

        if ($branding === null) {
            $branding = SchoolBranding::creer(
                schoolId: $schoolId,
                tenantId: $tenantId,
                createdAt: $this->clock->now(),
            );
        }

        return SchoolBrandingResource::fromDomain($branding);
    }
}
