<?php

declare(strict_types=1);

use App\Models\Project;
use App\Models\SupplierProject;
use App\Models\Tenant;
use App\Services\LeadRouter;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Tests\Concerns\SharesSupplierPdo;

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

beforeEach(function (): void {
    // Clear tenant context — LeadRouter operates without it (sharing across tenants).
    DB::statement("SELECT set_config('app.current_tenant_id', '0', true)");
});

it('does not match project for tenant with only balance_leads (no balance_rub)', function () {
    $tenant = Tenant::factory()->create([
        'balance_rub' => '0.00',
        'balance_leads' => 999, // legacy — должно игнорироваться после фикса
    ]);
    $project = Project::factory()->for($tenant)->create([
        'is_active' => true,
        'delivery_days_mask' => 127,
        'daily_limit_target' => 10,
        'delivered_today' => 0,
    ]);
    $sp = SupplierProject::factory()->create();
    \DB::table('project_supplier_links')->insert([
        'project_id' => $project->id,
        'supplier_project_id' => $sp->id,
        'platform' => $sp->platform,
        'subject_code' => null,
    ]);
    createRoutingSnapshotFromProject($project);

    $matched = app(LeadRouter::class)->matchEligibleProjects($sp);

    expect($matched)->toHaveCount(0); // balance_rub=0 → не eligible
});

it('matches project for tenant with balance_rub > 0 (balance_leads ignored)', function () {
    $tenant = Tenant::factory()->create([
        'balance_rub' => '500.00',
        'balance_leads' => 0,
    ]);
    $project = Project::factory()->for($tenant)->create([
        'is_active' => true,
        'delivery_days_mask' => 127,
        'daily_limit_target' => 10,
        'delivered_today' => 0,
    ]);
    $sp = SupplierProject::factory()->create();
    \DB::table('project_supplier_links')->insert([
        'project_id' => $project->id,
        'supplier_project_id' => $sp->id,
        'platform' => $sp->platform,
        'subject_code' => null,
    ]);
    createRoutingSnapshotFromProject($project);

    $matched = app(LeadRouter::class)->matchEligibleProjects($sp);

    expect($matched)->toHaveCount(1);
});
