<?php

namespace App\Livewire\Agent;

use App\Models\AgentLog;
use Livewire\Component;
use Livewire\WithPagination;

class Logs extends Component
{
    use WithPagination;

    public string $search     = '';
    public string $filterStatus = '';  // '' | success | failed | conflict | duplicate | processing

    public function updatedSearch(): void     { $this->resetPage(); }
    public function updatedFilterStatus(): void { $this->resetPage(); }

    public function render()
    {
        $userId = auth()->id();
        $tz     = auth()->user()->timezone ?? 'UTC';

        $query = AgentLog::where('user_id', $userId)->latest();

        if ($this->search !== '') {
            $query->where('input', 'like', '%' . $this->search . '%');
        }

        if ($this->filterStatus !== '') {
            $query->where('status', $this->filterStatus);
        }

        $logs = $query->paginate(25);

        // Monats-Statistiken
        $stats = AgentLog::where('user_id', $userId)
            ->where('created_at', '>=', now()->startOfMonth())
            ->selectRaw("
                count(*) as total,
                sum(credits) as credits_used,
                sum(cost_usd) as total_cost,
                sum(total_tokens) as total_tokens,
                sum(case when status = 'success' then 1 else 0 end) as successes,
                sum(case when status = 'failed' then 1 else 0 end) as failures,
                avg(duration_ms) as avg_duration
            ")
            ->first();

        // Credit-Limit für Fortschrittsanzeige
        $user  = auth()->user();
        $limit = $user->effective_limit;
        $usage = $user->effective_usage;
        $usagePercent = $user->usage_percent;

        return view('livewire.agent.logs', [
            'logs'         => $logs,
            'stats'        => $stats,
            'tz'           => $tz,
            'usage'        => $usage,
            'limit'        => $limit,
            'usagePercent' => $usagePercent,
        ])->layout('layouts.app');
    }
}
