<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AiRequest;
use Illuminate\Http\Request;
use Inertia\Inertia;

class AdminAiLogController extends Controller
{
    public function index(Request $request)
    {
        $query = AiRequest::with('activation.license.user');

        if ($search = $request->input('search')) {
            $query->where(function ($q) use ($search) {
                $q->where('prompt', 'like', "%{$search}%")
                  ->orWhere('domain', 'like', "%{$search}%");
            });
        }

        if ($domain = $request->input('domain')) {
            $query->where('domain', $domain);
        }

        $logs = $query->latest()->paginate(20)->through(fn ($log) => [
            'id' => $log->id,
            'domain' => $log->domain,
            'prompt' => $log->prompt,
            'request_type' => $log->request_type,
            'tokens_used' => $log->tokens_used,
            'response_time_ms' => $log->response_time_ms,
            'created_at' => $log->created_at->format('H:i:s'),
            'created_date' => $log->created_at->format('d M Y'),
        ]);

        $domains = AiRequest::select('domain')->distinct()->pluck('domain');

        return Inertia::render('Admin/AiLogs', [
            'logs' => $logs,
            'filters' => $request->only(['search', 'domain']),
            'domains' => $domains,
            'today_count' => AiRequest::whereDate('created_at', today())->count(),
            'today_tokens' => AiRequest::whereDate('created_at', today())->sum('tokens_used'),
        ]);
    }
}
