<?php

use App\Models\Email;
use App\Models\Import;
use App\Models\Person\PersonType;
use App\Models\User;
use App\Services\ImportProcessor;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

it('imports email contact when only email mapping is present', function () {
    // Authenticate a user so Person::creating can set user_id
    $user = User::factory()->create();
    Auth::login($user);

    // Minimal records for defaults used by ImportProcessor
    DB::table('person_groups')->insert([
        'name' => 'default',
        'description' => '',
        'color_tag' => null,
        'created_at' => now(),
        'updated_at' => now(),
    ]);
    PersonType::firstOrCreate(['name' => 'default'], ['description' => '']);

    // Put the sample CSV into the local storage the importer uses
    $uuid = (string) Str::uuid();
    $disk = 'local';
    $path = "imports/{$uuid}.csv";
    $content = file_get_contents(resource_path('examples/sample_import.csv'));
    Storage::disk($disk)->put($path, $content);

    // Create the import record
    $import = Import::create([
        'uuid' => $uuid,
        'user_id' => null,
        'import_template_id' => null,
        'client_id' => null,
        'source_type' => 'csv',
        'file_name' => basename($path),
        'original_name' => 'sample_import.csv',
        'disk' => $disk,
        'path' => $path,
        'size' => strlen($content),
        'status' => 'parsed',
        'meta' => [
            'has_header' => true,
            'detected_delimiter' => ',',
            'columns' => ['reference', 'first name', 'last name', 'address', 'phone number', 'email', 'invoice date', 'due date', 'amount'],
        ],
    ]);

    // Attach a single mapping: source 'email' -> target 'email.value', trim, apply both
    DB::table('import_mappings')->insert([
        'import_id' => $import->id,
        'entity' => 'emails',
        'source_column' => 'email',
        'target_field' => 'email.value',
        'transform' => 'trim',
        'apply_mode' => 'both',
        'options' => null,
        'position' => 1,
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    // Process the import
    $result = (new ImportProcessor)->process($import, null);
    expect($result['ok'])->toBeTrue();

    // Assert that the first row's email exists in the database
    expect(Email::where('value', 'john.doe@example.com')->exists())->toBeTrue();
});
