<?php

namespace App\Console\Commands;

use App\Models\WgTrafficSample;
use App\Services\WgStatus;
use Illuminate\Console\Command;

class WgSample extends Command
{
    protected $signature = 'clusev:wg-sample {--retention=7 : Days of history to keep}';

    protected $description = 'Persist a WireGuard traffic sample per peer (and prune old samples)';

    public function handle(WgStatus $wg): int
    {
        $status = $wg->read();

        if (($status['configured'] ?? false) && ! ($status['stale'] ?? true)) {
            $now = now();
            $rows = [];
            foreach ($status['peers'] ?? [] as $peer) {
                $rows[] = [
                    'peer_pubkey' => (string) ($peer['pubkey'] ?? ''),
                    'peer_name' => ($peer['name'] ?? '') !== '' ? (string) $peer['name'] : null,
                    'rx' => (int) ($peer['rx'] ?? 0),
                    'tx' => (int) ($peer['tx'] ?? 0),
                    'sampled_at' => $now,
                ];
            }
            if ($rows !== []) {
                WgTrafficSample::insert($rows);
            }
        }

        $retention = max(1, (int) $this->option('retention'));
        WgTrafficSample::where('sampled_at', '<', now()->subDays($retention))->delete();

        return self::SUCCESS;
    }
}
