<?php

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

uses(RefreshDatabase::class);

it('returns client cases when searching by contract reference', function () {
    // Arrange: create a user and authenticate
    $user = User::factory()->create();
    $this->actingAs($user);

    // Create a client case with a contract that has a known reference
    /** @var ClientCase $clientCase */
    $clientCase = ClientCase::factory()->create();

    /** @var Contract $contract */
    $contract = Contract::factory()->create([
        'client_case_id' => $clientCase->id,
        'reference' => 'REF-TEST-12345',
    ]);

    // Act: hit the global search route with the contract reference
    $response = $this->get(route('search', [
        'query' => 'REF-TEST-12345',
        'limit' => 8,
    ]));

    // Assert: response contains the affiliated case in "client_cases"
    $response->assertOk();
    $data = $response->json();

    expect($data)
        ->toHaveKey('client_cases')
        ->and(collect($data['client_cases'])->pluck('case_uuid')->all())
        ->toContain($clientCase->uuid);
});
