<?php

namespace App\Livewire\Pages\Ai;

use App\Domains\Ai\Services\AiService;
use App\Domains\Link\Models\Link;
use App\Domains\Workspace\Models\Workspace;
use Illuminate\View\View;
use Livewire\Component;

class Insights extends Component
{
    public string $insights = '';

    public bool $loading = false;

    public int $workspaceId = 0;

    public function mount(): void
    {
        $this->workspaceId = require_workspace()->id;
    }

    public function generate(): void
    {
        $workspace = Workspace::findOrFail($this->workspaceId);
        $this->loading = true;

        $topLinks = Link::where('workspace_id', $workspace->id)
            ->withCount('clicks')
            ->orderByDesc('clicks_count')
            ->limit(10)
            ->get(['slug', 'target_url', 'clicks_count']);

        $summary = $topLinks->map(fn ($l) => "{$l->slug}: {$l->clicks_count} clicks → {$l->target_url}")->implode("\n");

        $prompt = "You are a marketing analyst. Analyze these link performance stats and provide 3-5 actionable insights:\n\n{$summary}\n\nBe concise and specific.";

        $this->insights = app(AiService::class)->complete($prompt);
        $this->loading = false;
    }

    public function render(): View
    {
        return view('livewire.pages.ai.insights')
            ->layout('layouts.nimuli-app', ['title' => 'AI Insights']);
    }
}
