<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ApiClientKey;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ApiKeysController extends Controller
{
    public function index(Request $request): View
    {
        $keys = ApiClientKey::with('user:id,name,email,plan')
            ->when($request->filled('q'), function ($query) use ($request) {
                $term = $request->string('q')->value();
                $query->where('key_prefix', 'like', "%{$term}%")
                    ->orWhere('device_id', 'like', "%{$term}%")
                    ->orWhereHas('user', fn ($userQuery) => $userQuery
                        ->where('email', 'like', "%{$term}%")
                        ->orWhere('name', 'like', "%{$term}%"));
            })
            ->latest()
            ->paginate(25)
            ->withQueryString();

        $stats = [
            'total' => ApiClientKey::count(),
            'active' => ApiClientKey::where('is_active', true)->whereNull('revoked_at')->count(),
            'revoked' => ApiClientKey::whereNotNull('revoked_at')->count(),
            'recently_used' => ApiClientKey::where('last_used_at', '>=', now()->subDay())->count(),
        ];

        return view('admin.api-keys.index', compact('keys', 'stats'));
    }

    public function revoke(ApiClientKey $apiKey): RedirectResponse
    {
        $apiKey->update([
            'is_active' => false,
            'revoked_at' => now(),
        ]);

        return back()->with('success', 'API key revoked successfully.');
    }
}
