<?php

namespace Tests\Feature\Api;

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

class AgentHeartbeatTest extends TestCase
{
    use RefreshDatabase;

    private function deviceWithToken(?int $userId = null, array $extra = []): array
    {
        $token = bin2hex(random_bytes(32));
        $device = Device::create(array_merge([
            'user_id' => $userId,
            'name' => 'X', 'hostname' => 'X',
            'device_token_hash' => hash('sha256', $token),
        ], $extra));
        return [$device, $token];
    }

    public function test_unclaimed_heartbeat_returns_claimed_false(): void
    {
        [$device, $token] = $this->deviceWithToken(null);

        $response = $this->withHeader('Authorization', 'Bearer ' . $token)
            ->postJson('/api/agent/heartbeat', []);

        $response->assertOk()
            ->assertJsonPath('claimed', false);

        $this->assertTrue($device->fresh()->online);
        $this->assertNotNull($device->fresh()->last_seen_at);
    }

    public function test_claimed_heartbeat_returns_user_and_name(): void
    {
        $user = User::factory()->create();
        [$device, $token] = $this->deviceWithToken($user->id, ['name' => 'Akshit-PC']);

        $response = $this->withHeader('Authorization', 'Bearer ' . $token)
            ->postJson('/api/agent/heartbeat', []);

        $response->assertOk()
            ->assertJsonPath('claimed', true)
            ->assertJsonPath('name', 'Akshit-PC');
    }

    public function test_invalid_token_returns_401(): void
    {
        $this->withHeader('Authorization', 'Bearer nope')
            ->postJson('/api/agent/heartbeat', [])
            ->assertStatus(401);
    }
}
