<?php

namespace Tests\Feature\Api;

use App\Models\Device;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class AgentRegisterTest extends TestCase
{
    use RefreshDatabase;

    public function test_agent_can_register_and_get_pairing_code(): void
    {
        $response = $this->postJson('/api/agent/register', [
            'hostname' => 'MY-PC',
            'os_info' => 'Windows 11 Pro 23H2',
            'local_ip' => '192.168.1.42',
        ]);

        $response->assertCreated()
            ->assertJsonStructure(['pairing_code', 'device_token', 'expires_at'])
            ->assertJsonPath('pairing_code', fn ($v) => (bool) preg_match('/^\d{3}-\d{3}$/', $v));

        $this->assertDatabaseHas('devices', ['hostname' => 'MY-PC', 'user_id' => null]);
        $this->assertSame(1, Device::count());
    }

    public function test_pairing_code_expires_in_10_minutes(): void
    {
        $response = $this->postJson('/api/agent/register', [
            'hostname' => 'X', 'os_info' => 'Y', 'local_ip' => '10.0.0.1',
        ]);

        $expires = $response->json('expires_at');
        $diff = strtotime($expires) - time();
        $this->assertGreaterThan(580, $diff);
        $this->assertLessThan(620, $diff);
    }

    public function test_hostname_is_required(): void
    {
        $this->postJson('/api/agent/register', ['os_info' => 'X', 'local_ip' => '10.0.0.1'])
            ->assertStatus(422);
    }
}
