<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Domain\Model\HomeworkRules\HomeworkRules;
use App\Administration\Domain\Repository\HomeworkRulesRepository;
use App\Administration\Infrastructure\Api\Resource\HomeworkRulesResource;
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 des règles de devoirs.
 *
 * @implements ProviderInterface<HomeworkRulesResource>
 */
final readonly class HomeworkRulesProvider implements ProviderInterface
{
    public function __construct(
        private HomeworkRulesRepository $homeworkRulesRepository,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
        private Clock $clock,
    ) {
    }

    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): HomeworkRulesResource
    {
        if (!$this->authorizationChecker->isGranted('ROLE_ADMIN')) {
            throw new AccessDeniedHttpException('Seuls les administrateurs peuvent gérer les règles de devoirs.');
        }

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

        $tenantId = $this->tenantContext->getCurrentTenantId();
        $homeworkRules = $this->homeworkRulesRepository->findByTenantId($tenantId);

        if ($homeworkRules === null) {
            $homeworkRules = HomeworkRules::creer(
                tenantId: $tenantId,
                now: $this->clock->now(),
            );
            $this->homeworkRulesRepository->save($homeworkRules);
        }

        return HomeworkRulesResource::fromDomain($homeworkRules);
    }
}
