<?php

declare(strict_types=1);

namespace App\Support\ProductTelemetry;

use App\Models\ProductUsageEvent;
use DateTimeInterface;
use Illuminate\Support\Carbon;

final class ProductTelemetrySummaryQuery
{
    public function __construct(private readonly ProductUsageEventCatalog $catalog) {}

    /**
     * @return array{
     *     window: array{start_at: string, end_at: string},
     *     active_workspaces: int,
     *     total_events: int,
     *     families: array<string, array{label: string, count: int}>
     * }
     */
    public function summarize(DateTimeInterface $startAt, ?DateTimeInterface $endAt = null): array
    {
        $startAt = Carbon::instance($startAt);
        $endAt = Carbon::instance($endAt ?? now());

        $baseQuery = ProductUsageEvent::query()
            ->where('occurred_at', '>=', $startAt)
            ->where('occurred_at', '<=', $endAt);

        /** @var array<string, int> $counts */
        $counts = (clone $baseQuery)
            ->selectRaw('event_name, COUNT(*) as aggregate')
            ->groupBy('event_name')
            ->pluck('aggregate', 'event_name')
            ->map(static fn (mixed $count): int => (int) $count)
            ->all();

        $families = [];
        $totalEvents = 0;

        foreach ($this->catalog->visibleFamilies() as $eventName => $label) {
            $count = (int) ($counts[$eventName] ?? 0);
            $totalEvents += $count;

            $families[$eventName] = [
                'label' => $label,
                'count' => $count,
            ];
        }

        return [
            'window' => [
                'start_at' => $startAt->toIso8601String(),
                'end_at' => $endAt->toIso8601String(),
            ],
            'active_workspaces' => (clone $baseQuery)
                ->distinct()
                ->count('workspace_id'),
            'total_events' => $totalEvents,
            'families' => $families,
        ];
    }
}
