<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Infrastructure\Security\SecurityUser;
use App\Scolarite\Domain\Model\Evaluation\EvaluationId;
use App\Scolarite\Domain\Repository\EvaluationRepository;
use App\Scolarite\Infrastructure\Api\Resource\CompetencyEvaluationResource;
use App\Shared\Infrastructure\Tenant\TenantContext;

use function array_map;

use Doctrine\DBAL\Connection;

use function is_string;

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<CompetencyEvaluationResource>
 */
final readonly class CompetencyEvaluationCollectionProvider implements ProviderInterface
{
    public function __construct(
        private Connection $connection,
        private EvaluationRepository $evaluationRepository,
        private TenantContext $tenantContext,
        private Security $security,
    ) {
    }

    /** @return array<CompetencyEvaluationResource> */
    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): array
    {
        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 $evaluationIdStr */
        $evaluationIdStr = $uriVariables['evaluationId'] ?? '';

        if (!is_string($evaluationIdStr) || $evaluationIdStr === '') {
            throw new NotFoundHttpException('Évaluation non trouvée.');
        }

        $tenantId = $this->tenantContext->getCurrentTenantId();
        $evaluationId = EvaluationId::fromString($evaluationIdStr);

        $evaluation = $this->evaluationRepository->findById($evaluationId, $tenantId);

        if ($evaluation === null) {
            throw new NotFoundHttpException('Évaluation non trouvée.');
        }

        if ((string) $evaluation->teacherId !== $user->userId()) {
            throw new AccessDeniedHttpException('Accès refusé.');
        }

        $rows = $this->connection->fetchAllAssociative(
            'SELECT ce.id, ce.evaluation_id, ce.competency_id,
                    c.code AS competency_code, c.name AS competency_name
             FROM competency_evaluations ce
             JOIN competencies c ON c.id = ce.competency_id
             WHERE ce.evaluation_id = :evaluation_id
             ORDER BY c.sort_order ASC',
            ['evaluation_id' => $evaluationIdStr],
        );

        return array_map(static function (array $row): CompetencyEvaluationResource {
            $resource = new CompetencyEvaluationResource();
            /** @var string $id */
            $id = $row['id'];
            $resource->id = $id;
            /** @var string $evaluationId */
            $evaluationId = $row['evaluation_id'];
            $resource->evaluationId = $evaluationId;
            /** @var string $competencyId */
            $competencyId = $row['competency_id'];
            $resource->competencyId = $competencyId;
            /** @var string $code */
            $code = $row['competency_code'];
            $resource->competencyCode = $code;
            /** @var string $name */
            $name = $row['competency_name'];
            $resource->competencyName = $name;

            return $resource;
        }, $rows);
    }
}
