<?php

declare(strict_types=1);

namespace App\Administration\Application\Service\Import;

use App\Shared\Domain\Tenant\TenantId;
use Doctrine\DBAL\Connection;

/**
 * Charge les enseignants existants d'un tenant
 * afin de détecter les doublons à l'import.
 */
final readonly class ExistingTeacherFinder
{
    public function __construct(
        private Connection $connection,
    ) {
    }

    /**
     * @return list<array{firstName: string, lastName: string, email: string}>
     */
    public function findAllForTenant(TenantId $tenantId): array
    {
        $sql = <<<'SQL'
            SELECT u.first_name, u.last_name, u.email
            FROM users u
            WHERE u.tenant_id = :tenant_id
              AND u.roles::jsonb @> :role
            SQL;

        /** @var list<array{first_name: string, last_name: string, email: string}> $rows */
        $rows = $this->connection->fetchAllAssociative($sql, [
            'tenant_id' => (string) $tenantId,
            'role' => '"ROLE_PROF"',
        ]);

        return array_map(
            static fn (array $row) => [
                'firstName' => $row['first_name'],
                'lastName' => $row['last_name'],
                'email' => $row['email'],
            ],
            $rows,
        );
    }
}
