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

    /** @return array<GradeResource> */
    #[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;

        // Return all students in the class, with LEFT JOIN to grades
        $rows = $this->connection->fetchAllAssociative(
            'SELECT u.id AS student_id, u.first_name, u.last_name,
                    g.id AS grade_id, g.evaluation_id, g.value, g.status AS grade_status,
                    g.appreciation
             FROM class_assignments ca
             JOIN users u ON u.id = ca.user_id
             LEFT JOIN grades g ON g.student_id = u.id AND g.evaluation_id = :evaluation_id AND g.tenant_id = :tenant_id
             WHERE ca.school_class_id = :class_id
             AND ca.tenant_id = :tenant_id
             ORDER BY u.last_name ASC, u.first_name ASC',
            [
                'evaluation_id' => $evaluationIdStr,
                'tenant_id' => (string) $tenantId,
                'class_id' => $classId,
            ],
        );

        return array_map(static function (array $row) use ($evaluationIdStr): GradeResource {
            $resource = new GradeResource();
            /** @var string $studentId */
            $studentId = $row['student_id'];
            /** @var string|null $gradeId */
            $gradeId = $row['grade_id'] ?? null;
            $resource->id = $gradeId ?? 'pending-' . $studentId;
            $resource->evaluationId = $evaluationIdStr;
            $resource->studentId = $studentId;
            /** @var string|null $firstName */
            $firstName = $row['first_name'] ?? null;
            /** @var string|null $lastName */
            $lastName = $row['last_name'] ?? null;
            $resource->studentName = $firstName !== null && $lastName !== null
                ? $lastName . ' ' . $firstName
                : null;
            /** @var string|float|null $valueRaw */
            $valueRaw = $row['value'] ?? null;
            $resource->value = $valueRaw !== null ? (float) $valueRaw : null;
            /** @var string|null $gradeStatus */
            $gradeStatus = $row['grade_status'] ?? null;
            $resource->status = $gradeStatus;
            /** @var string|null $appreciation */
            $appreciation = $row['appreciation'] ?? null;
            $resource->appreciation = $appreciation;

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