<?php

namespace Tests\Feature\Api;

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

class DeviceUpdateDestroyTest extends TestCase
{
    use RefreshDatabase;

    public function test_user_can_rename_own_device(): void
    {
        $user = User::factory()->create();
        $device = Device::create(['user_id' => $user->id, 'name' => 'Old', 'hostname' => 'X', 'device_token_hash' => str_repeat('1', 64)]);
        Sanctum::actingAs($user);

        $this->patchJson("/api/devices/{$device->id}", ['name' => 'Living Room PC'])->assertOk();
        $this->assertSame('Living Room PC', $device->fresh()->name);
    }

    public function test_user_cannot_rename_others_device(): void
    {
        $owner = User::factory()->create();
        $other = User::factory()->create();
        $device = Device::create(['user_id' => $owner->id, 'name' => 'X', 'hostname' => 'X', 'device_token_hash' => str_repeat('2', 64)]);
        Sanctum::actingAs($other);

        $this->patchJson("/api/devices/{$device->id}", ['name' => 'Hacked'])->assertStatus(404);
        $this->assertSame('X', $device->fresh()->name);
    }

    public function test_user_can_delete_own_device(): void
    {
        $user = User::factory()->create();
        $device = Device::create(['user_id' => $user->id, 'name' => 'Z', 'hostname' => 'Z', 'device_token_hash' => str_repeat('3', 64)]);
        Sanctum::actingAs($user);

        $this->deleteJson("/api/devices/{$device->id}")->assertOk();
        $this->assertDatabaseMissing('devices', ['id' => $device->id]);
    }

    public function test_user_cannot_delete_others_device(): void
    {
        $owner = User::factory()->create();
        $other = User::factory()->create();
        $device = Device::create(['user_id' => $owner->id, 'name' => 'Y', 'hostname' => 'Y', 'device_token_hash' => str_repeat('4', 64)]);
        Sanctum::actingAs($other);

        $this->deleteJson("/api/devices/{$device->id}")->assertStatus(404);
        $this->assertDatabaseHas('devices', ['id' => $device->id]);
    }
}
