<?php

use App\Models\Email;
use App\Models\Import;
use App\Models\ImportTemplate;
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('detects columns using an explicit delimiter', function () {
    // Prepare file with semicolon delimiter
    $uuid = (string) Str::uuid();
    $disk = 'local';
    $path = "imports/{$uuid}.csv";
    $csv = "email;reference\nalpha@example.com;REF-1\n";
    Storage::disk($disk)->put($path, $csv);

    $import = Import::create([
        'uuid' => $uuid,
        'user_id' => null,
        'import_template_id' => null,
        'client_id' => null,
        'source_type' => 'csv',
        'file_name' => basename($path),
        'original_name' => 'semicolon.csv',
        'disk' => $disk,
        'path' => $path,
        'size' => strlen($csv),
        'status' => 'uploaded',
        'meta' => ['has_header' => true],
    ]);

    $response = test()->getJson(route('imports.columns', ['import' => $import->id, 'has_header' => 1, 'delimiter' => ';']));
    $response->assertSuccessful();
    $data = $response->json();
    expect($data['detected_delimiter'])->toBe(';');
    expect($data['columns'])->toBe(['email', 'reference']);
});

it('processes using template default delimiter when provided', 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' => '']);

    // Template with semicolon as default delimiter
    $template = ImportTemplate::create([
        'uuid' => (string) Str::uuid(),
        'name' => 'Semicolon CSV',
        'source_type' => 'csv',
        'default_record_type' => null,
        'user_id' => $user->id,
        'client_id' => null,
        'is_active' => true,
        'sample_headers' => ['email', 'reference'],
        'meta' => ['delimiter' => ';'],
    ]);

    // Put a semicolon CSV file
    $uuid = (string) Str::uuid();
    $disk = 'local';
    $path = "imports/{$uuid}.csv";
    $csv = "email;reference\njohn.delim@example.com;R-100\n";
    Storage::disk($disk)->put($path, $csv);

    $import = Import::create([
        'uuid' => $uuid,
        'user_id' => $user->id,
        'import_template_id' => $template->id,
        'client_id' => null,
        'source_type' => 'csv',
        'file_name' => basename($path),
        'original_name' => 'semicol.csv',
        'disk' => $disk,
        'path' => $path,
        'size' => strlen($csv),
        'status' => 'parsed',
        // columns present to allow mapping by header name
        'meta' => ['has_header' => true, 'columns' => ['email', 'reference']],
    ]);

    // Map email -> email.value
    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(),
    ]);

    $result = (new ImportProcessor)->process($import, $user);
    expect($result['ok'])->toBeTrue();
    expect(Email::where('value', 'john.delim@example.com')->exists())->toBeTrue();
});
