<?php

declare(strict_types=1);

use App\Models\SupplierLead;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\Concerns\SharesSupplierPdo;

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

it('allows supplier_leads with vid=NULL (CSV-recovered leads)', function (): void {
    $lead = SupplierLead::create([
        'supplier_project_id' => null,
        'platform' => 'B1',
        'phone' => '79991234567',
        'vid' => null,
        'raw_payload' => ['project' => 'B1_a.com', 'tag' => 't', 'phone' => '79991234567'],
        'received_at' => now(),
        'source' => 'csv_recovery',
        'recovered_from_csv_at' => now(),
    ]);

    expect($lead->id)->toBeGreaterThan(0);
    expect($lead->fresh()->vid)->toBeNull();
});

it('allows multiple supplier_leads with vid=NULL under the UNIQUE index', function (): void {
    foreach (['79990000001', '79990000002', '79990000003'] as $phone) {
        SupplierLead::create([
            'supplier_project_id' => null,
            'platform' => 'B1',
            'phone' => $phone,
            'vid' => null,
            'raw_payload' => ['project' => 'B1_a.com', 'phone' => $phone],
            'received_at' => now(),
            'source' => 'csv_recovery',
            'recovered_from_csv_at' => now(),
        ]);
    }

    expect(SupplierLead::whereNull('vid')->count())->toBeGreaterThanOrEqual(3);
});

it('still accepts a real numeric vid for webhook leads', function (): void {
    $lead = SupplierLead::create([
        'supplier_project_id' => null,
        'platform' => 'B1',
        'phone' => '79991234567',
        'vid' => 432176649,
        'raw_payload' => ['vid' => 432176649, 'project' => 'B1_a.com'],
        'received_at' => now(),
        'source' => 'webhook',
    ]);

    expect($lead->fresh()->vid)->toBe(432176649);
});
