<?php

namespace Tests\Feature\Api;

use App\Http\Controllers\Api\DeviceController;
use App\Models\Device;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class DeviceStreamTest extends TestCase
{
    use RefreshDatabase;

    public function test_snapshot_returns_only_users_devices(): void
    {
        $user = User::factory()->create();
        $other = User::factory()->create();

        $own = Device::create(['user_id' => $user->id, 'name' => 'A', 'hostname' => 'A', 'device_token_hash' => str_repeat('1', 64), 'online' => true]);
        Device::create(['user_id' => $other->id, 'name' => 'B', 'hostname' => 'B', 'device_token_hash' => str_repeat('2', 64), 'online' => true]);

        $controller = new DeviceController();
        $snapshot = $controller->snapshotFor($user);

        $this->assertCount(1, $snapshot);
        $this->assertArrayHasKey($own->id, $snapshot);
        $this->assertSame(true, $snapshot[$own->id]['online']);
    }

    public function test_diff_returns_only_changed_devices(): void
    {
        $controller = new DeviceController();
        $previous = [
            1 => ['id' => 1, 'name' => 'A', 'online' => true,  'last_seen_at' => null],
            2 => ['id' => 2, 'name' => 'B', 'online' => false, 'last_seen_at' => null],
        ];
        $current = [
            1 => ['id' => 1, 'name' => 'A', 'online' => false, 'last_seen_at' => null],
            2 => ['id' => 2, 'name' => 'B', 'online' => false, 'last_seen_at' => null],
        ];
        $diff = $controller->diffSnapshots($previous, $current);
        $this->assertCount(1, $diff);
        $this->assertSame(1, $diff[0]['id']);
    }

    public function test_stream_endpoint_returns_event_stream_content_type(): void
    {
        $user = User::factory()->create();
        $token = $user->createToken('test')->plainTextToken;

        $response = $this->withHeader('Authorization', 'Bearer ' . $token)
            ->withHeader('X-Test-Tick-Limit', '1')
            ->get('/api/devices/stream');

        $this->assertSame('text/event-stream', $response->headers->get('content-type'));
    }

    public function test_stream_accepts_token_via_query_string(): void
    {
        $user = User::factory()->create();
        $token = $user->createToken('test')->plainTextToken;

        $response = $this->withHeader('X-Test-Tick-Limit', '1')
            ->get('/api/devices/stream?token=' . $token);

        $response->assertOk()
            ->assertHeader('content-type', 'text/event-stream');
    }

    public function test_stream_rejects_no_token(): void
    {
        $this->get('/api/devices/stream')->assertStatus(401);
    }
}
