<?php

namespace Tests\Feature;

use App\Models\User;
use App\Services\WgStatus;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class WgStatusTest extends TestCase
{
    use RefreshDatabase;

    private string $file;

    protected function setUp(): void
    {
        parent::setUp();
        $dir = storage_path('app/restart-signal');
        @mkdir($dir, 0775, true);
        $this->file = $dir.'/wg-status.json';
        @unlink($this->file);
    }

    protected function tearDown(): void
    {
        @unlink($this->file);
        parent::tearDown();
    }

    public function test_absent_file_reads_as_unconfigured(): void
    {
        $s = app(WgStatus::class)->read();
        $this->assertFalse($s['configured']);
        $this->assertTrue($s['stale']);
    }

    public function test_parses_a_configured_status_with_peers(): void
    {
        file_put_contents($this->file, json_encode([
            'at' => time(),
            'configured' => true,
            'gate' => ['marker' => true, 'chain' => true],
            'wg_quick' => 'active',
            'server' => ['subnet' => '10.99.0.0/24', 'server_ip' => '10.99.0.1', 'port' => 51820, 'endpoint' => '1.2.3.4:51820', 'pubkey' => 'srvpub'],
            'peers' => [
                ['name' => 'laptop', 'pubkey' => 'p1', 'endpoint' => '5.6.7.8:41820', 'latest_handshake' => time(), 'rx' => 100, 'tx' => 200],
                ['name' => 'phone', 'pubkey' => 'p2', 'endpoint' => '', 'latest_handshake' => 0, 'rx' => 0, 'tx' => 0],
            ],
        ]));

        $s = app(WgStatus::class)->read();
        $this->assertTrue($s['configured']);
        $this->assertFalse($s['stale']);
        $this->assertTrue($s['gate']['marker']);
        $this->assertSame(51820, $s['server']['port']);
        $this->assertCount(2, $s['peers']);
        $this->assertTrue($s['peers'][0]['online']);
        $this->assertFalse($s['peers'][1]['online']);
    }

    public function test_stale_when_at_is_old(): void
    {
        file_put_contents($this->file, json_encode(['at' => time() - 999, 'configured' => true, 'peers' => []]));
        $this->assertTrue(app(WgStatus::class)->read()['stale']);
    }

    public function test_route_requires_auth_and_returns_status(): void
    {
        $this->get('/wg-status.json')->assertRedirect('/login');

        file_put_contents($this->file, json_encode(['at' => time(), 'configured' => false]));
        $this->actingAs(User::factory()->create(['must_change_password' => false]))
            ->getJson('/wg-status.json')->assertOk()->assertJson(['configured' => false]);
    }
}
