<?php

use App\Models\ClientCase;
use App\Models\Contract;
use App\Models\Document;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

function makeCaseWithContractAndDoc(): array
{
    $case = ClientCase::factory()->create();
    $contract = Contract::factory()->for($case, 'clientCase')->create();
    $doc = Document::factory()->create();
    // Assign the document to the case initially
    $doc->documentable_type = ClientCase::class;
    $doc->documentable_id = $case->id;
    $doc->save();

    return [$case, $contract, $doc];
}

it('reassigns document to a contract within the same case', function () {
    $user = User::factory()->create();
    [$case, $contract, $doc] = makeCaseWithContractAndDoc();

    $this->actingAs($user)
        ->patch(route('clientCase.document.update', [$case->uuid, $doc->uuid]), [
            'contract_uuid' => $contract->uuid,
        ])
        ->assertRedirect();

    $doc->refresh();
    expect($doc->documentable_type)->toBe(Contract::class)
        ->and($doc->documentable_id)->toBe($contract->id);
});

it('returns validation error when assigning to a contract from another case', function () {
    $user = User::factory()->create();
    // Source case
    [$caseA, $contractA, $doc] = makeCaseWithContractAndDoc();
    // Different case and its contract
    $caseB = ClientCase::factory()->create();
    $contractB = Contract::factory()->for($caseB, 'clientCase')->create();

    $this->actingAs($user)
        ->from(route('clientCase.show', $caseA->uuid))
        ->patch(route('clientCase.document.update', [$caseA->uuid, $doc->uuid]), [
            'contract_uuid' => $contractB->uuid,
        ])
        ->assertSessionHasErrors('contract_uuid');

    $doc->refresh();
    // Still belongs to the original case
    expect($doc->documentable_type)->toBe(ClientCase::class)
        ->and($doc->documentable_id)->toBe($caseA->id);
});

it('keeps or moves document to the case when contract_uuid is null/empty', function () {
    $user = User::factory()->create();
    [$case, $contract, $doc] = makeCaseWithContractAndDoc();

    $this->actingAs($user)
        ->from(route('clientCase.show', $case->uuid))
        ->patch(route('clientCase.document.update', [$case->uuid, $doc->uuid]), [
            // Simulate select "— Brez —" which typically posts an empty string
            'contract_uuid' => '',
        ])
        ->assertRedirect();

    $doc->refresh();
    expect($doc->documentable_type)->toBe(ClientCase::class)
        ->and($doc->documentable_id)->toBe($case->id);
});
