<?php

use App\Models\User;
use Illuminate\Support\Str;

uses(\Illuminate\Foundation\Testing\RefreshDatabase::class);

test('user gets UUID automatically when created', function () {
    $user = User::factory()->create();
    
    expect($user->uuid)->not->toBeNull();
    expect(Str::isUuid((string) $user->uuid))->toBeTrue();
});

test('user UUID is unique', function () {
    $user1 = User::factory()->create();
    $user2 = User::factory()->create();
    
    expect($user1->uuid)->not->toBe($user2->uuid);
});

test('user UUID cannot be duplicated', function () {
    $user1 = User::factory()->create();
    
    expect(function () use ($user1) {
        User::create([
            'name' => 'Test User',
            'email' => 'test2@example.com', 
            'password' => bcrypt('password'),
            'uuid' => $user1->uuid
        ]);
    })->toThrow(\Illuminate\Database\QueryException::class);
});

test('user UUID can be manually set during creation', function () {
    $customUuid = Str::uuid();
    
    $user = User::create([
        'name' => 'Test User',
        'email' => 'test@example.com',
        'password' => bcrypt('password'),
        'uuid' => $customUuid
    ]);
    
    expect($user->uuid)->toBe($customUuid);
});

test('user UUID is not overwritten if already set', function () {
    $customUuid = Str::uuid();
    
    $user = new User([
        'name' => 'Test User',
        'email' => 'test@example.com',
        'password' => bcrypt('password'),
        'uuid' => $customUuid
    ]);
    
    $user->save();
    
    expect($user->uuid)->toBe($customUuid);
});

test('existing users can have UUIDs added via migration', function () {
    // This test verifies that the migration properly adds UUIDs to existing users
    // We can't easily test the migration directly, but we can test that users
    // created without UUIDs in the factory would get them via the boot method
    
    $user = new User([
        'name' => 'Test User',
        'email' => 'test@example.com',
        'password' => bcrypt('password'),
    ]);
    
    // Don't set UUID, let the boot method handle it
    $user->save();
    
    expect($user->uuid)->not->toBeNull();
    expect(Str::isUuid((string) $user->uuid))->toBeTrue();
});