<?php

use App\Models\DeviceToken;
use App\Models\User;

test('guest cannot register device token', function () {
    $this->postJson('/api/v1/devices/register', [
        'token' => 'some-fcm-token',
        'platform' => 'android',
    ])->assertUnauthorized();
});

test('authenticated user can register device token', function () {
    $user = User::factory()->create();

    $this->actingAs($user, 'sanctum')
        ->postJson('/api/v1/devices/register', [
            'token' => 'fcm-token-'.uniqid(),
            'platform' => 'android',
            'device_name' => 'Samsung Galaxy',
            'app_version' => '1.2.3',
        ])->assertOk()
        ->assertJsonPath('status', 'success')
        ->assertJsonStructure(['data' => ['device_id']]);
});

test('duplicate token upserts without error', function () {
    $user = User::factory()->create();
    $token = 'fcm-stable-token';

    $this->actingAs($user, 'sanctum')
        ->postJson('/api/v1/devices/register', ['token' => $token, 'platform' => 'ios'])
        ->assertOk();

    // Second call with same token — should update, not duplicate
    $this->actingAs($user, 'sanctum')
        ->postJson('/api/v1/devices/register', ['token' => $token, 'platform' => 'ios'])
        ->assertOk();

    expect(DeviceToken::where('token', $token)->count())->toBe(1);
});

test('authenticated user can unregister device token', function () {
    $user = User::factory()->create();
    $token = 'fcm-token-to-remove';

    DeviceToken::create([
        'user_id' => $user->id,
        'token' => $token,
        'platform' => 'android',
    ]);

    $this->actingAs($user, 'sanctum')
        ->deleteJson('/api/v1/devices/unregister', ['token' => $token])
        ->assertOk();

    expect(DeviceToken::where('token', $token)->exists())->toBeFalse();
});
