<?php

use App\Models\ArchiveSetting;
use App\Models\ClientCase;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

uses(RefreshDatabase::class);

it('reactivates a single contract when a reactivate rule exists', function () {
    $user = User::factory()->create();
    test()->actingAs($user);

    $case = ClientCase::factory()->create(['active' => 1]);
    $typeId = DB::table('contract_types')->insertGetId([
        'name' => 'Standard',
        'description' => 'Test',
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    $contract = $case->contracts()->create([
        'uuid' => (string) Str::uuid(),
        'reference' => 'T-REACT',
        'start_date' => now()->toDateString(),
        'end_date' => null,
        'type_id' => $typeId,
        'active' => 0, // initially archived
        'deleted_at' => now(), // also soft deleted to test clearing
    ]);

    ArchiveSetting::factory()->create([
        'entities' => [
            ['table' => 'contracts', 'conditions' => ['where' => ['client_case_id' => $case->id]]],
        ],
        'strategy' => 'immediate',
        'soft' => true,
        'enabled' => true,
        'reactivate' => true,
    ]);

    test()->post(route('clientCase.contract.archive', ['client_case' => $case->uuid, 'uuid' => $contract->uuid]))
        ->assertRedirect();

    $contract->refresh();
    expect($contract->active)->toBe(1)
        ->and($contract->deleted_at)->toBeNull();
});
