<?php

declare(strict_types=1);

use App\Models\ImportLog;
use App\Models\ImportUnknownStatus;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;

uses(DatabaseTransactions::class);

beforeEach(function (): void {
    $this->tenant = Tenant::factory()->create();
    $this->user = User::factory()->for($this->tenant)->create();
    DB::statement('SET app.current_tenant_id = '.$this->tenant->id);
});

test('ImportLog создаётся с дефолтами и кастует mapping_config/dry_run', function (): void {
    $log = ImportLog::create([
        'tenant_id' => $this->tenant->id,
        'user_id' => $this->user->id,
        'filename' => 'leads.csv',
        'file_path' => 'imports/1/uuid.csv',
        'mapping_config' => ['status' => ['Новые' => 'new']],
        'dry_run' => true,
    ]);

    expect($log->status)->toBe('pending')
        ->and($log->entity_type)->toBe('leads')
        ->and($log->dry_run)->toBeTrue()
        ->and($log->mapping_config)->toBe(['status' => ['Новые' => 'new']]);
});

test('ImportUnknownStatus хранит маппинг и фильтруется scope unresolved', function (): void {
    ImportUnknownStatus::create([
        'tenant_id' => $this->tenant->id,
        'status_ru' => 'Архив',
        'occurrences' => 3,
    ]);
    ImportUnknownStatus::create([
        'tenant_id' => $this->tenant->id,
        'status_ru' => 'Спам',
        'occurrences' => 1,
        'mapped_to_slug' => 'lost',
        'resolved_at' => now(),
    ]);

    expect(ImportUnknownStatus::unresolved()->count())->toBe(1)
        ->and(ImportUnknownStatus::unresolved()->first()->status_ru)->toBe('Архив');
});
