<?php

declare(strict_types=1);

use App\Models\SupplierLead;
use App\Models\SupplierProject;
use App\Services\DaData\DaDataPhoneClient;
use App\Services\LeadRegionResolver;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\Concerns\SharesSupplierPdo;
use Tests\Support\Imitation\FakeDaDataPhoneClient;

uses(DatabaseTransactions::class);
uses(SharesSupplierPdo::class);

/**
 * FakeDaDataPhoneClient — детерминированный фейк для тестов каскада региона.
 * Класс живёт в Tests\Support\Imitation\ (тестовое пространство имён).
 *
 * Task 1: Подставной DaData-клиент (group imitation).
 */
it('resolves region via dadata stub qc=0 for Москва', function (): void {
    config(['services.dadata.enabled' => true]);

    $fake = new FakeDaDataPhoneClient;
    $fake->stub('79990000077', qc: 0, region: 'Москва', provider: 'МТС');

    app()->instance(DaDataPhoneClient::class, $fake);

    $sp = SupplierProject::factory()->create();
    $lead = SupplierLead::factory()->create([
        'supplier_project_id' => $sp->id,
        'phone' => '79990000077',
        'raw_payload' => ['tag' => ''],
    ]);

    $res = app(LeadRegionResolver::class)->resolve($lead);

    expect($res->source)->toBe('dadata')
        ->and($res->subjectCode)->toBe(82); // Москва = код 82
})->group('imitation');

it('fake dadata phone client stub method returns self for fluent api', function (): void {
    $fake = new FakeDaDataPhoneClient;
    $result = $fake->stub('79990000001', qc: 0, region: 'Москва', provider: null);
    expect($result)->toBeInstanceOf(FakeDaDataPhoneClient::class);
})->group('imitation');

it('falls through to tag-fallback on qc=2 stub (empty tag → unknown)', function (): void {
    config(['services.dadata.enabled' => true]);

    $fake = new FakeDaDataPhoneClient;
    // qc=2 → мусор/иностранец → резолвер сразу уходит на tag-fallback (Россвязь не зовётся).
    $fake->stub('79990000077', qc: 2, region: null, provider: null);

    app()->instance(DaDataPhoneClient::class, $fake);

    $sp = SupplierProject::factory()->create();
    $lead = SupplierLead::factory()->create([
        'supplier_project_id' => $sp->id,
        'phone' => '79990000077',
        'raw_payload' => ['tag' => ''],
    ]);

    $res = app(LeadRegionResolver::class)->resolve($lead);

    // Пустой тег → tagCode=null → source='unknown' (см. LeadRegionResolver::tagFallback)
    expect($res->source)->toBe('unknown')
        ->and($res->subjectCode)->toBeNull();
})->group('imitation');
