<?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 Anomalies extends Component
{
    public string $report = '';

    public bool $loading = false;

    public int $workspaceId = 0;

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

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

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

        $summary = $links->map(fn ($l) => "{$l->slug}: {$l->clicks_count} clicks, created {$l->created_at->diffForHumans()}")->implode("\n");

        $prompt = "You are a security and analytics expert. Look for anomalies, suspicious patterns, or unusual traffic in these link stats. Flag anything that seems off:\n\n{$summary}\n\nList anomalies or say 'No anomalies detected' if traffic looks normal.";

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

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