<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Service;

use App\Scolarite\Application\Port\ClassStudentsReader;
use App\Shared\Domain\Tenant\TenantId;

use function array_map;

use Doctrine\DBAL\Connection;
use Override;

final readonly class DoctrineClassStudentsReader implements ClassStudentsReader
{
    public function __construct(
        private Connection $connection,
    ) {
    }

    #[Override]
    public function studentsInClass(string $classId, TenantId $tenantId): array
    {
        /** @var array<array{id: string, first_name: string, last_name: string}> $rows */
        $rows = $this->connection->fetchAllAssociative(
            'SELECT u.id, u.first_name, u.last_name
             FROM class_assignments ca
             JOIN users u ON u.id = ca.user_id
             WHERE ca.school_class_id = :class_id
             AND ca.tenant_id = :tenant_id
             ORDER BY u.last_name ASC, u.first_name ASC',
            [
                'class_id' => $classId,
                'tenant_id' => (string) $tenantId,
            ],
        );

        return array_map(
            static fn (array $row): array => [
                'id' => $row['id'],
                'name' => $row['first_name'] . ' ' . $row['last_name'],
            ],
            $rows,
        );
    }
}
