<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Service;

use App\Scolarite\Application\Port\ScheduleDisplayReader;
use Doctrine\DBAL\ArrayParameterType;
use Doctrine\DBAL\Connection;
use Override;

/**
 * Résout les noms d'affichage des matières et enseignants via des requêtes batch.
 */
final readonly class DoctrineScheduleDisplayReader implements ScheduleDisplayReader
{
    public function __construct(
        private Connection $connection,
    ) {
    }

    #[Override]
    public function subjectDisplay(string $tenantId, string ...$subjectIds): array
    {
        if ($subjectIds === []) {
            return [];
        }

        $rows = $this->connection->fetchAllAssociative(
            'SELECT id, name, color FROM subjects WHERE id IN (:ids) AND tenant_id = :tenantId',
            ['ids' => $subjectIds, 'tenantId' => $tenantId],
            ['ids' => ArrayParameterType::STRING],
        );

        $display = [];

        foreach ($rows as $row) {
            /** @var string $id */
            $id = $row['id'];
            /** @var string $name */
            $name = $row['name'];
            /** @var string|null $color */
            $color = $row['color'];
            $display[$id] = ['name' => $name, 'color' => $color];
        }

        return $display;
    }

    #[Override]
    public function teacherNames(string $tenantId, string ...$teacherIds): array
    {
        if ($teacherIds === []) {
            return [];
        }

        $rows = $this->connection->fetchAllAssociative(
            'SELECT id, first_name, last_name FROM users WHERE id IN (:ids) AND tenant_id = :tenantId',
            ['ids' => $teacherIds, 'tenantId' => $tenantId],
            ['ids' => ArrayParameterType::STRING],
        );

        $names = [];

        foreach ($rows as $row) {
            /** @var string $id */
            $id = $row['id'];
            /** @var string $firstName */
            $firstName = $row['first_name'];
            /** @var string $lastName */
            $lastName = $row['last_name'];
            $names[$id] = $firstName . ' ' . $lastName;
        }

        return $names;
    }
}
