<?php

namespace App\Http\Controllers;

use App\Jobs\PollRouterJob;
use App\Models\Router;
use App\Models\RouterInterface;

class RouterMetricsController extends Controller
{
    public function metrics(Router $router)
    {
        $router->refresh();
        $stat = $router->stats()->latest('collected_at')->first();

        return response()->json([
            'status' => $router->status,
            'last_seen' => optional($router->last_seen)->toDateTimeString(),
            'cpu_load' => (int)($router->cpu_load ?? $stat?->cpu_load ?? 0),
            'memory' => [
                'free'  => (int)$router->free_memory,
                'total' => (int)$router->total_memory,
            ],
            'hdd' => [
                'free'  => (int)$router->free_hdd,
                'total' => (int)$router->total_hdd,
            ],
            'uptime_seconds' => (int)($router->uptime_seconds ?? 0),
            'model' => $router->model,
            'board_name' => $router->board_name,
            'serial' => $router->serial,
        ]);
    }

    public function interfaces(Router $router)
    {
        $ifaces = $router->interfaces()->orderBy('name')->get(['name','enabled','running','rx_bps','tx_bps']);
        return response()->json($ifaces);
    }

    public function pollNow(Router $router)
    {
        dispatch(new PollRouterJob($router));
        return response()->json(['ok'=>true]);
    }
}
