<?php

use App\Models\Email;
use App\Models\Import;
use App\Models\ImportEntity;
use App\Models\Person\Person;
use App\Models\User;
use Illuminate\Support\Facades\Storage;

it('simulates generic entities with deduplication and filtering', function () {
    Storage::fake('local');
    // Ensure import_entities seeds (or minimal row) exist
    ImportEntity::query()->firstOrCreate(['key' => 'emails'], [
        'canonical_root' => 'email',
        'label' => 'Emails',
        'fields' => ['value'],
    ]);

    // Existing email to trigger duplicate_db (attach minimal person)
    $person = Person::factory()->create();
    Email::create(['value' => 'test@example.com', 'person_id' => $person->id]);

    $csv = "email\nTest@example.com"; // will normalize to same identity
    Storage::disk('local')->put('imports/sample.csv', $csv);

    $import = Import::create([
        'uuid' => (string) Str::uuid(),
        'user_id' => User::factory()->create()->id,
        'import_template_id' => null,
        'client_id' => null,
        'source_type' => 'csv',
        'file_name' => 'sample.csv',
        'original_name' => 'sample.csv',
        'disk' => 'local',
        'path' => 'imports/sample.csv',
        'size' => strlen($csv),
        'status' => 'uploaded',
        'meta' => [
            'has_header' => true,
            'columns' => ['email'],
        ],
    ]);

    // Mapping: email.value -> column email
    \DB::table('import_mappings')->insert([
        'import_id' => $import->id,
        'source_column' => 'email',
        'target_field' => 'email.value',
        'position' => 0,
    ]);

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

    expect($result['entities'])->toContain('email');
    expect($result['summaries']['email']['total_rows'])->toBe(1);
    // Because existing duplicate in DB
    expect($result['summaries']['email']['duplicate_db'] ?? 0)->toBe(1);
});
