<?php

use App\Models\Account;
use App\Models\Contract;
use App\Models\Email;
use App\Models\Import;
use App\Models\Person\Person;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

uses(RefreshDatabase::class);

it('simulates multiple roots with duplicate flags', function () {
    $user = User::factory()->create();
    Auth::login($user);

    $contract = Contract::factory()->create(['reference' => 'C-1']);
    $typeId = DB::table('account_types')->insertGetId(['name' => 'Current', 'description' => 'Test', 'created_at' => now(), 'updated_at' => now()]);
    $account = Account::create(['reference' => 'A-1', 'contract_id' => $contract->id, 'type_id' => $typeId]);

    Email::factory()->create(['value' => 'test@example.com', 'person_id' => Person::factory()->create()->id]);

    $csv = implode("\n", [
        'contract_ref,account_ref,payment_ref,email_value,payment_amount',
        'C-1,A-1,P-1,test@example.com,10',
        'C-1,A-1,P-1,NEW@example.com,10',
        'C-1,A-1,P-2,test@example.com,15',
    ]);

    Storage::fake('local');
    Storage::disk('local')->put('imports/test.csv', $csv);

    $import = Import::factory()->create([
        'disk' => 'local',
        'path' => 'imports/test.csv',
        'meta' => [
            'has_header' => true,
            'forced_delimiter' => ',',
        ],
    ]);

    DB::table('import_mappings')->insert([
        ['import_id' => $import->id, 'source_column' => 'contract_ref', 'target_field' => 'contract.reference', 'position' => 1],
        ['import_id' => $import->id, 'source_column' => 'account_ref',  'target_field' => 'account.reference',  'position' => 2],
        ['import_id' => $import->id, 'source_column' => 'payment_ref',  'target_field' => 'payment.reference',  'position' => 3],
        ['import_id' => $import->id, 'source_column' => 'email_value',  'target_field' => 'email.value',        'position' => 4],
        ['import_id' => $import->id, 'source_column' => 'payment_amount', 'target_field' => 'payment.amount',    'position' => 5],
    ]);

    $service = app(\App\Services\ImportSimulationService::class);
    $result = $service->simulate($import, 100, false);

    expect($result['entities'])->toContain('contract', 'account', 'payment', 'email');
    expect($result['rows'][0]['entities']['email']['duplicate_db'] ?? false)->toBeTrue();
    expect($result['rows'][1]['entities']['payment']['status'])->toBe('duplicate');
    expect($result['rows'][2]['entities']['payment']['status'])->toBe('ok');
});
