<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\CronRunLog;
use App\Models\PerformanceMetric;
use App\Models\User;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\DB;

class PerformanceController extends Controller
{
    public function index(): View
    {
        return view('admin.performance', [
            'summary' => [
                'users' => User::query()->where('role', 'user')->count(),
                'orders' => DB::table('orders')->count(),
                'wallet_transactions' => DB::table('wallet_transactions')->count(),
                'failed_jobs' => DB::table('failed_jobs')->count(),
                'pending_jobs' => DB::table('jobs')->count(),
                'last_successful_cron' => CronRunLog::query()->where('status', 'success')->latest('started_at')->value('started_at'),
            ],
            'recentCrons' => CronRunLog::query()->latest('id')->limit(30)->get(),
            'metrics' => PerformanceMetric::query()->latest('recorded_at')->limit(100)->get(),
        ]);
    }

    public function snapshot(): RedirectResponse
    {
        $points = [
            ['system', 'users_total', (float) User::query()->where('role', 'user')->count(), 'count'],
            ['system', 'orders_total', (float) DB::table('orders')->count(), 'count'],
            ['system', 'wallet_transactions_total', (float) DB::table('wallet_transactions')->count(), 'count'],
            ['queue', 'pending_jobs', (float) DB::table('jobs')->count(), 'count'],
            ['queue', 'failed_jobs', (float) DB::table('failed_jobs')->count(), 'count'],
        ];

        $now = now();
        foreach ($points as [$group, $key, $value, $unit]) {
            PerformanceMetric::query()->create([
                'metric_group' => $group,
                'metric_key' => $key,
                'metric_value' => $value,
                'unit' => $unit,
                'recorded_at' => $now,
            ]);
        }

        return back()->with('status', 'Performance snapshot captured.');
    }
}
