<?php

namespace Tests\Feature;

use App\Models\WgTrafficSample;
use App\Services\WgTraffic;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class WgTrafficTest extends TestCase
{
    use RefreshDatabase;

    private function sample(string $pk, int $rx, int $tx, int $agoSeconds): void
    {
        WgTrafficSample::create([
            'peer_pubkey' => $pk, 'peer_name' => $pk, 'rx' => $rx, 'tx' => $tx,
            'sampled_at' => now()->subSeconds($agoSeconds),
        ]);
    }

    public function test_empty_when_no_samples(): void
    {
        $s = app(WgTraffic::class)->series(3600, 6);
        $this->assertSame(0, $s['total_down']);
        $this->assertSame(0, $s['total_up']);
        $this->assertCount(6, $s['points']);
        $this->assertSame(0, array_sum(array_column($s['points'], 'down')));
    }

    public function test_aggregates_positive_deltas_across_peers(): void
    {
        $this->sample('A', 0, 0, 3000);
        $this->sample('A', 100, 10, 1800);
        $this->sample('A', 300, 30, 600);
        $this->sample('B', 0, 0, 3000);
        $this->sample('B', 50, 5, 600);

        $s = app(WgTraffic::class)->series(3600, 6);
        // Both directions are THROUGHPUT (sum of positive per-peer deltas), not raw counters:
        // down = A(100+200)+B(50) = 350 ; up = A(10+20)+B(5) = 35.
        $this->assertSame(350, $s['total_down']);
        $this->assertSame(35, $s['total_up']);
        $this->assertGreaterThan(0, $s['peak_down']);
    }

    public function test_counter_reset_clamps_to_zero(): void
    {
        $this->sample('A', 500, 0, 1800);
        $this->sample('A', 20, 0, 600);

        $s = app(WgTraffic::class)->series(3600, 6);
        $this->assertSame(0, $s['total_down']);
    }
}
