<?php

namespace Tests\Feature\Api;

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

class AgentAuthMiddlewareTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        Route::middleware('auth.agent')->get('/test/agent-ping', fn (\Illuminate\Http\Request $r) => [
            'device_id' => $r->attributes->get('device')->id,
        ]);
    }

    public function test_valid_token_passes(): void
    {
        $token = bin2hex(random_bytes(32));
        $device = Device::create([
            'name' => 'X', 'hostname' => 'X',
            'device_token_hash' => hash('sha256', $token),
        ]);

        $this->withHeader('Authorization', 'Bearer ' . $token)
            ->getJson('/test/agent-ping')
            ->assertOk()
            ->assertJsonPath('device_id', $device->id);
    }

    public function test_missing_token_returns_401(): void
    {
        $this->getJson('/test/agent-ping')->assertStatus(401);
    }

    public function test_unknown_token_returns_401(): void
    {
        $this->withHeader('Authorization', 'Bearer wrong-token')
            ->getJson('/test/agent-ping')
            ->assertStatus(401);
    }
}
