<?php

declare(strict_types=1);

use App\Mail\BalanceFrozenMail;
use App\Models\PricingTier;
use App\Models\Project;
use App\Models\Tenant;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Tests\Concerns\SharesSupplierPdo;

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

beforeEach(function () {
    DB::statement("SELECT set_config('app.current_tenant_id', '0', true)");
    PricingTier::query()->create([
        'tier_no' => 1,
        'leads_in_tier' => null,
        'price_per_lead_kopecks' => 5000,
        'is_active' => true,
        'effective_from' => now(),
    ]);
});

it('freezes pre-existing underfunded tenant on first run', function () {
    Mail::fake();
    // 0₽ + проекты на 25 лидов → должен быть заморожен.
    $tenant = Tenant::factory()->create(['balance_rub' => '0.00', 'frozen_by_balance_at' => null]);
    Project::factory()->for($tenant)->create(['is_active' => true, 'daily_limit_target' => 25]);

    $this->artisan('billing:preflight-initial-sweep')->assertSuccessful();

    expect($tenant->fresh()->frozen_by_balance_at)->not->toBeNull();
    Mail::assertQueued(BalanceFrozenMail::class, fn ($mail) => $mail->tenant->id === $tenant->id);
});
