<?php

namespace App\Services\Engagement;

use App\Models\PromptUsageStat;
use Illuminate\Support\Str;

final class PromptUsageService
{
    public function record(string $prompt): void
    {
        $trimmed = trim($prompt);
        if ($trimmed === '') {
            return;
        }

        $normalized = mb_strtolower(mb_substr($trimmed, 0, 500));
        $signature = hash('sha256', $normalized);
        $preview = Str::limit($trimmed, 160);

        $stat = PromptUsageStat::query()->firstOrNew(['signature' => $signature]);
        $stat->preview = $preview;
        $stat->use_count = (int) $stat->use_count + 1;
        $stat->last_used_at = now();
        $stat->save();
    }

    /**
     * @return array<int, array{preview: string, use_count: int, last_used_at: ?string}>
     */
    public function trending(int $limit = 10): array
    {
        $rows = PromptUsageStat::query()
            ->orderByDesc('use_count')
            ->orderByDesc('last_used_at')
            ->limit($limit)
            ->get(['preview', 'use_count', 'last_used_at']);

        return $rows->map(fn ($r) => [
            'preview' => (string) $r->preview,
            'use_count' => (int) $r->use_count,
            'last_used_at' => $r->last_used_at?->toIso8601String(),
        ])->all();
    }
}
