<?php

use App\Models\Document;
use App\Models\Group;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

test('删除分组时将关联的专用文档设置为孤立状态', function () {
    // 创建测试数据
    $user = User::factory()->create();
    $group = Group::factory()->create(['name' => '测试分组']);
    
    // 创建属于该分组的专用文档
    $document1 = Document::factory()->create([
        'type' => 'dedicated',
        'group_id' => $group->id,
        'uploaded_by' => $user->id,
        'title' => '专用文档1',
    ]);
    
    $document2 = Document::factory()->create([
        'type' => 'dedicated',
        'group_id' => $group->id,
        'uploaded_by' => $user->id,
        'title' => '专用文档2',
    ]);
    
    // 创建全局文档（不应受影响）
    $globalDocument = Document::factory()->create([
        'type' => 'global',
        'group_id' => null,
        'uploaded_by' => $user->id,
        'title' => '全局文档',
    ]);
    
    // 验证文档初始状态
    expect($document1->fresh()->group_id)->toBe($group->id);
    expect($document2->fresh()->group_id)->toBe($group->id);
    expect($globalDocument->fresh()->group_id)->toBeNull();
    
    // 删除分组
    $group->delete();
    
    // 验证专用文档的 group_id 已被设置为 null
    expect($document1->fresh()->group_id)->toBeNull();
    expect($document2->fresh()->group_id)->toBeNull();
    
    // 验证全局文档不受影响
    expect($globalDocument->fresh()->group_id)->toBeNull();
    
    // 验证文档本身没有被删除
    expect(Document::find($document1->id))->not->toBeNull();
    expect(Document::find($document2->id))->not->toBeNull();
    expect(Document::find($globalDocument->id))->not->toBeNull();
});

test('删除分组不影响其他分组的文档', function () {
    // 创建测试数据
    $user = User::factory()->create();
    $group1 = Group::factory()->create(['name' => '分组1']);
    $group2 = Group::factory()->create(['name' => '分组2']);
    
    // 创建属于分组1的文档
    $document1 = Document::factory()->create([
        'type' => 'dedicated',
        'group_id' => $group1->id,
        'uploaded_by' => $user->id,
    ]);
    
    // 创建属于分组2的文档
    $document2 = Document::factory()->create([
        'type' => 'dedicated',
        'group_id' => $group2->id,
        'uploaded_by' => $user->id,
    ]);
    
    // 删除分组1
    $group1->delete();
    
    // 验证分组1的文档变为孤立状态
    expect($document1->fresh()->group_id)->toBeNull();
    
    // 验证分组2的文档不受影响
    expect($document2->fresh()->group_id)->toBe($group2->id);
});

test('删除没有文档的分组不会出错', function () {
    // 创建一个没有文档的分组
    $group = Group::factory()->create(['name' => '空分组']);
    
    // 删除分组应该成功且不抛出异常
    expect(fn() => $group->delete())->not->toThrow(Exception::class);
    
    // 验证分组已被删除
    expect(Group::find($group->id))->toBeNull();
});
