<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Domain\Repository\ClassRepository;
use App\Administration\Domain\Repository\SubjectRepository;
use App\Administration\Infrastructure\Security\SecurityUser;
use App\Scolarite\Domain\Model\Homework\HomeworkId;
use App\Scolarite\Domain\Repository\HomeworkRepository;
use App\Scolarite\Domain\Repository\HomeworkRuleExceptionRepository;
use App\Scolarite\Infrastructure\Api\Resource\HomeworkResource;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

/**
 * @implements ProviderInterface<HomeworkResource>
 */
final readonly class HomeworkItemProvider implements ProviderInterface
{
    public function __construct(
        private HomeworkRepository $homeworkRepository,
        private HomeworkRuleExceptionRepository $exceptionRepository,
        private TenantContext $tenantContext,
        private Security $security,
        private ClassRepository $classRepository,
        private SubjectRepository $subjectRepository,
    ) {
    }

    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): HomeworkResource
    {
        if (!$this->tenantContext->hasTenant()) {
            throw new UnauthorizedHttpException('Bearer', 'Tenant non défini.');
        }

        $user = $this->security->getUser();

        if (!$user instanceof SecurityUser) {
            throw new UnauthorizedHttpException('Bearer', 'Authentification requise.');
        }

        /** @var string $id */
        $id = $uriVariables['id'];

        $homework = $this->homeworkRepository->findById(
            HomeworkId::fromString($id),
            $this->tenantContext->getCurrentTenantId(),
        );

        if ($homework === null) {
            throw new NotFoundHttpException('Devoir non trouvé.');
        }

        if ((string) $homework->teacherId !== $user->userId()) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas le propriétaire de ce devoir.');
        }

        $class = $this->classRepository->findById($homework->classId);
        $subject = $this->subjectRepository->findById($homework->subjectId);
        $tenantId = $this->tenantContext->getCurrentTenantId();
        $exceptions = $this->exceptionRepository->findByHomework($homework->id, $tenantId);

        return HomeworkResource::fromDomain(
            $homework,
            $class !== null ? (string) $class->name : null,
            $subject !== null ? (string) $subject->name : null,
            $exceptions[0] ?? null,
        );
    }
}
