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

    /** @return array<CompetencyResultResource> */
    #[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é.');
        }

        $classId = (string) $evaluation->classId;

        // Matrice : élèves x compétences avec LEFT JOIN sur les résultats
        $rows = $this->connection->fetchAllAssociative(
            'SELECT u.id AS student_id, u.first_name, u.last_name,
                    ce.id AS competency_evaluation_id, ce.competency_id,
                    c.code AS competency_code, c.name AS competency_name,
                    scr.id AS result_id, scr.level_code
             FROM class_assignments ca
             JOIN users u ON u.id = ca.user_id
             CROSS JOIN competency_evaluations ce
             JOIN competencies c ON c.id = ce.competency_id
             LEFT JOIN student_competency_results scr
                 ON scr.competency_evaluation_id = ce.id
                 AND scr.student_id = u.id
                 AND scr.tenant_id = :tenant_id
             WHERE ca.school_class_id = :class_id
             AND ca.tenant_id = :tenant_id
             AND ce.evaluation_id = :evaluation_id
             ORDER BY u.last_name ASC, u.first_name ASC, c.sort_order ASC',
            [
                'evaluation_id' => $evaluationIdStr,
                'tenant_id' => (string) $tenantId,
                'class_id' => $classId,
            ],
        );

        return array_map(static function (array $row) use ($evaluationIdStr): CompetencyResultResource {
            $resource = new CompetencyResultResource();
            /** @var string $studentId */
            $studentId = $row['student_id'];
            /** @var string|null $resultId */
            $resultId = $row['result_id'];
            /** @var string $ceId */
            $ceId = $row['competency_evaluation_id'];
            /** @var string $competencyId */
            $competencyId = $row['competency_id'];
            $resource->id = $resultId ?? 'pending-' . $studentId . '-' . $ceId;
            $resource->evaluationId = $evaluationIdStr;
            $resource->competencyEvaluationId = $ceId;
            $resource->competencyId = $competencyId;
            /** @var string $competencyCode */
            $competencyCode = $row['competency_code'];
            $resource->competencyCode = $competencyCode;
            /** @var string $competencyName */
            $competencyName = $row['competency_name'];
            $resource->competencyName = $competencyName;
            $resource->studentId = $studentId;
            /** @var string|null $firstName */
            $firstName = $row['first_name'];
            /** @var string|null $lastName */
            $lastName = $row['last_name'];
            $resource->studentName = $lastName . ' ' . $firstName;
            /** @var string|null $levelCode */
            $levelCode = $row['level_code'];
            $resource->levelCode = $levelCode;

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