<?php

use App\Models\Activity;
use App\Models\ClientCase;
use App\Models\Contract;
use App\Models\FieldJob;
use App\Models\FieldJobSetting;
use App\Models\User;

it('bulk assigns multiple contracts and skips already assigned', function () {
    $user = User::factory()->create();
    $assignee = User::factory()->create();
    $this->actingAs($user);

    // Minimal related data
    $case = ClientCase::factory()->create();
    $c1 = Contract::factory()->create(['client_case_id' => $case->id]);
    $c2 = Contract::factory()->create(['client_case_id' => $case->id]);
    $c3 = Contract::factory()->create(['client_case_id' => $case->id]);

    // Existing active assignment for c3
    $setting = FieldJobSetting::factory()->create([
        'segment_id' => 1,
        'action_id' => 1,
        'assign_decision_id' => 1,
        'complete_decision_id' => 1,
        'return_segment_id' => 1,
        'queue_segment_id' => 1,
    ]);
    FieldJob::create([
        'field_job_setting_id' => $setting->id,
        'assigned_user_id' => $assignee->id,
        'contract_id' => $c3->id,
        'assigned_at' => now(),
    ]);

    // Post bulk assign
    $resp = $this->post(route('fieldjobs.assign-bulk'), [
        'contract_uuids' => [$c1->uuid, $c2->uuid, $c3->uuid],
        'assigned_user_id' => $assignee->id,
    ]);

    $resp->assertRedirect();

    // c1 and c2 should have active jobs
    expect(FieldJob::where('contract_id', $c1->id)->whereNull('cancelled_at')->whereNull('completed_at')->exists())->toBeTrue();
    expect(FieldJob::where('contract_id', $c2->id)->whereNull('cancelled_at')->whereNull('completed_at')->exists())->toBeTrue();
    // c3 should still have only one active job
    expect(FieldJob::where('contract_id', $c3->id)->whereNull('cancelled_at')->whereNull('completed_at')->count())->toBe(1);

    // Activities were created for c1 and c2 (two records)
    expect(Activity::where('contract_id', $c1->id)->exists())->toBeTrue();
    expect(Activity::where('contract_id', $c2->id)->exists())->toBeTrue();
});
