<?php

declare(strict_types=1);

use App\Jobs\Supplier\SyncSupplierProjectsJob;
use App\Models\Project;
use App\Models\Tenant;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\Concerns\SharesSupplierPdo;

// Изоляция: persistent liderra_testing, RefreshDatabase off. DatabaseTransactions
// откатывает pgsql после теста; SharesSupplierPdo делает pgsql_supplier общим PDO
// с pgsql, иначе query через Project::on('pgsql_supplier') не видит uncommitted
// tenant/project (паттерн Спека B / AutoPauseFlowTest).
uses(DatabaseTransactions::class);
uses(SharesSupplierPdo::class);

it('excludes projects of frozen tenants from supplier order', function () {
    $frozenTenant = Tenant::factory()->create(['frozen_by_balance_at' => now()]);
    $frozenProject = Project::factory()->for($frozenTenant)->create(['is_active' => true, 'daily_limit_target' => 50]);
    insertSnapshotForTomorrow($frozenProject);

    $activeTenant = Tenant::factory()->create(['frozen_by_balance_at' => null]);
    $activeProject = Project::factory()->for($activeTenant)->create(['is_active' => true, 'daily_limit_target' => 30]);
    insertSnapshotForTomorrow($activeProject);

    $eligible = app(SyncSupplierProjectsJob::class)->collectEligibleProjects();

    $tenantIds = $eligible->pluck('tenant_id')->unique()->all();
    expect($tenantIds)->not->toContain($frozenTenant->id);
    expect($tenantIds)->toContain($activeTenant->id);
});

it('excludes individually preflight-blocked projects', function () {
    $tenant = Tenant::factory()->create(['frozen_by_balance_at' => null]);
    $okProject = Project::factory()->for($tenant)->create(['is_active' => true, 'daily_limit_target' => 30, 'preflight_blocked_at' => null]);
    insertSnapshotForTomorrow($okProject);
    $blocked = Project::factory()->for($tenant)->create(['is_active' => true, 'daily_limit_target' => 20, 'preflight_blocked_at' => now()]);

    $eligible = app(SyncSupplierProjectsJob::class)->collectEligibleProjects();

    $ids = $eligible->pluck('id')->all();
    expect($ids)->toContain($okProject->id);
    expect($ids)->not->toContain($blocked->id);
});
