<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\BotRuntimeState;
use App\Models\BotSetting;
use App\Models\Instrument;
use App\Models\MarketTick;
use App\Models\SystemLog;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Artisan;
use Illuminate\View\View;

class AdminDashboardController extends Controller
{
    public function index(): View
    {
        return view('admin.dashboard', [
            'pageTitle' => 'Admin Panel',
            'pageSubtitle' => 'System management and data sync',
            'stats' => [
                'users' => User::where('role', 'user')->count(),
                'connected_brokers' => User::whereHas('brokerAccount', fn ($q) => $q->where('is_connected', true))->count(),
                'active_bots' => BotSetting::where('auto_trade', true)->count(),
                'instruments' => Instrument::where('is_active', true)->count(),
                'last_tick' => MarketTick::latest('tick_at')->value('tick_at'),
            ],
            'workers' => BotRuntimeState::all(),
            'marketFeed' => app(\App\Services\FlatTrade\BrokerAccountResolver::class)->marketFeedAccount(),
            'users' => User::with(['brokerAccount', 'botSettings'])->latest()->get(),
        ]);
    }

    public function syncData(): RedirectResponse
    {
        Artisan::call('market:sync');
        Artisan::call('flattrade:sync-accounts');

        SystemLog::create([
            'channel' => 'admin',
            'level' => 'info',
            'message' => 'Manual market + account sync triggered',
        ]);

        return back()->with('status', 'Market data and all user accounts synced.');
    }

    public function logs(): View
    {
        return view('admin.logs', [
            'pageTitle' => 'System Logs',
            'pageSubtitle' => 'Worker and sync activity',
            'logs' => SystemLog::latest()->paginate(50),
        ]);
    }
}
