<?php

declare(strict_types=1);

use App\Models\Deal;
use App\Models\Project;
use App\Models\SupplierLead;
use App\Models\SupplierProject;
use App\Models\Tenant;
use App\Services\DaData\DaDataPhoneClient;
use Database\Seeders\PricingTierSeeder;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Tests\Concerns\SharesSupplierPdo;
use Tests\Support\Imitation\FakeDaDataPhoneClient;
use Tests\Support\Imitation\LeadInjector;

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

beforeEach(function (): void {
    $this->seed(PricingTierSeeder::class);

    // DaData stub: phone '79991112233' resolves to Moscow (code 82)
    $fake = new FakeDaDataPhoneClient;
    $fake->stub('79991112233', qc: 0, region: 'Москва', provider: 'МТС');
    app()->instance(DaDataPhoneClient::class, $fake);

    config([
        'services.dadata.enabled' => true,
        'services.dadata.api_key' => 'k',
        'services.dadata.secret' => 's',
        'services.dadata.daily_cap_rub' => 100000,
    ]);
});

it('site() creates SupplierLead, dispatches job, returns processed lead with a deal', function (): void {
    // Arrange: supplier project for vashinvestor.ru
    $supplier = SupplierProject::factory()->create([
        'platform' => 'B1',
        'signal_type' => 'site',
        'unique_key' => 'vashinvestor.ru',
    ]);

    // Arrange: tenant with enough balance
    $tenant = Tenant::factory()->create(['balance_leads' => 0, 'balance_rub' => '1000.00']);

    // Arrange: project linked to supplier, with daily limit and snapshot
    $project = Project::factory()->create([
        'tenant_id' => $tenant->id,
        'signal_type' => 'site',
        'signal_identifier' => 'vashinvestor.ru',
        'is_active' => true,
        'delivered_today' => 0,
        'delivered_in_month' => 0,
        'delivery_days_mask' => 127,
        'daily_limit_target' => 10,
        'effective_daily_limit_today' => null,
    ]);
    linkProjectToSupplier($project, $supplier);
    createRoutingSnapshotFromProject($project, null, 'site', 'vashinvestor.ru');

    // Act: inject a synthetic site lead (dispatchSync = synchronous)
    $lead = (new LeadInjector)->site(
        domain: 'vashinvestor.ru',
        phone: '79991112233',
        tag: 'Москва',
        platform: 'B1',
        vid: 5_000_001,
    );

    // Assert: SupplierLead processed
    expect($lead)->toBeInstanceOf(SupplierLead::class);
    expect($lead->processed_at)->not->toBeNull('SupplierLead should be processed after dispatchSync');
    expect((string) $lead->phone)->toBe('79991112233');
    expect($lead->vid)->toBe(5_000_001);

    // Assert: deal created in tenant context (BYPASSRLS connection already shares PDO)
    $deals = DB::connection('pgsql_supplier')
        ->table('deals')
        ->where('tenant_id', $tenant->id)
        ->where('source_crm_id', 5_000_001)
        ->get();

    expect($deals)->toHaveCount(1, 'Expected exactly 1 deal to be created for the tenant');
    expect((string) $deals->first()->phone)->toBe('79991112233');
})->group('imitation');
