<?php

declare(strict_types=1);

namespace App\SuperAdmin\Application\Query\GetEstablishmentsMetrics;

use Doctrine\DBAL\Connection;

/**
 * Returns anonymized aggregate metrics for all establishments.
 * No personal data (names, emails, grades) is ever exposed.
 */
final readonly class GetEstablishmentsMetricsHandler
{
    public function __construct(
        private Connection $connection,
    ) {
    }

    /**
     * @return EstablishmentMetricsView[]
     */
    public function __invoke(GetEstablishmentsMetricsQuery $query): array
    {
        $rows = $this->connection->fetchAllAssociative(
            <<<'SQL'
                SELECT
                    e.id AS establishment_id,
                    e.name,
                    e.status,
                    COALESCE(m.user_count, 0) AS user_count,
                    COALESCE(m.student_count, 0) AS student_count,
                    COALESCE(m.teacher_count, 0) AS teacher_count,
                    m.last_login_at
                FROM establishments e
                LEFT JOIN establishment_metrics m ON m.establishment_id = e.id
                ORDER BY e.name ASC
            SQL,
        );

        return array_map(
            static function (array $row): EstablishmentMetricsView {
                /** @var string $establishmentId */
                $establishmentId = $row['establishment_id'];
                /** @var string $name */
                $name = $row['name'];
                /** @var string $status */
                $status = $row['status'];
                /** @var int $userCount */
                $userCount = $row['user_count'];
                /** @var int $studentCount */
                $studentCount = $row['student_count'];
                /** @var int $teacherCount */
                $teacherCount = $row['teacher_count'];
                /** @var string|null $lastLoginAt */
                $lastLoginAt = $row['last_login_at'];

                return new EstablishmentMetricsView(
                    establishmentId: $establishmentId,
                    name: $name,
                    status: $status,
                    userCount: $userCount,
                    studentCount: $studentCount,
                    teacherCount: $teacherCount,
                    lastLoginAt: $lastLoginAt,
                );
            },
            $rows,
        );
    }
}
