<?php

use App\Models\Client;
use App\Models\Import;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

uses(RefreshDatabase::class);

it('deduplicates client cases by client_ref when importing', function () {
    // Ensure base seeds for reference tables
    \Illuminate\Support\Facades\Artisan::call('db:seed', ['--force' => true]);
    $user = User::factory()->create();
    Auth::login($user);

    // Prepare client and a small CSV with two rows sharing same client_ref but different contract.reference
    $client = Client::factory()->create();
    Storage::fake('local');
    $csv = "client_ref,contract.reference,contract.description\nCASE-001,REF-1,First\nCASE-001,REF-2,Second\n";
    Storage::disk('local')->put('imports/test.csv', $csv);

    $import = Import::create([
        'uuid' => (string) Str::uuid(),
        'user_id' => $user->id,
        'client_id' => $client->id,
        'source_type' => 'csv',
        'file_name' => 'test.csv',
        'original_name' => 'test.csv',
        'disk' => 'local',
        'path' => 'imports/test.csv',
        'status' => 'queued',
        'meta' => ['has_header' => true, 'columns' => ['client_ref', 'contract.reference', 'contract.description']],
        'import_template_id' => null,
    ]);

    // Mapping: map client_ref to client_case.client_ref and contract fields
    DB::table('import_mappings')->insert([
        'import_id' => $import->id,
        'source_column' => 'client_ref',
        'target_field' => 'client_case.client_ref',
        'transform' => 'trim|upper',
        'apply_mode' => 'both',
        'options' => null,
        'position' => 0,
        'created_at' => now(),
        'updated_at' => now(),
    ]);
    DB::table('import_mappings')->insert([
        'import_id' => $import->id,
        'source_column' => 'contract.reference',
        'target_field' => 'contract.reference',
        'transform' => 'trim|upper|ref',
        'apply_mode' => 'both',
        'options' => null,
        'position' => 1,
        'created_at' => now(),
        'updated_at' => now(),
    ]);
    DB::table('import_mappings')->insert([
        'import_id' => $import->id,
        'source_column' => 'contract.description',
        'target_field' => 'contract.description',
        'transform' => 'trim',
        'apply_mode' => 'both',
        'options' => null,
        'position' => 2,
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    // Process
    $service = app(\App\Services\ImportProcessor::class);
    $service->process($import, $user);

    // There should be exactly one client case for CASE-001 and two contracts under it
    $ccs = \App\Models\ClientCase::where('client_id', $client->id)->where('client_ref', 'CASE-001')->get();
    // Ensure at least one exists
    expect($ccs->count())->toBeGreaterThanOrEqual(1);
    // Dedup to 1
    expect($ccs->count())->toBe(1);
    $contracts = \App\Models\Contract::where('client_case_id', $ccs->first()->id)->get();
    expect($contracts->count())->toBe(2);
});
