<?php

declare(strict_types=1);

use App\Jobs\SyncSupplierProjectJob;
use App\Models\PricingTier;
use App\Models\Project;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Queue;
use Tests\Concerns\SharesSupplierPdo;

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

beforeEach(function () {
    Queue::fake();
    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, // 50₽/лид — capacity = balance/50
        'is_active' => true,
        'effective_from' => now(),
    ]);
});

it('returns 409 when new project would overload balance', function () {
    // 1000₽ / 50₽ = 20 лидов capacity; запрашиваем daily_limit_target=30 → дефицит 10.
    $tenant = Tenant::factory()->withRequisites()->create(['balance_rub' => '1000.00']);
    $user = User::factory()->create(['tenant_id' => $tenant->id]);

    $response = $this->actingAs($user)->postJson('/api/projects', [
        'name' => 'Перегрузка',
        'signal_type' => 'site',
        'signal_identifier' => 'overload.ru',
        'daily_limit_target' => 30,
        'regions' => [],
        'delivery_days_mask' => 127,
    ]);

    $response->assertStatus(409);
    $response->assertJsonPath('error', 'balance_insufficient');
    $response->assertJsonPath('deficit_leads', 10);
    $response->assertJsonPath('current_capacity_leads', 20);
    $response->assertJsonPath('would_be_required_leads', 30);
    expect(Project::where('signal_identifier', 'overload.ru')->exists())->toBeFalse();
});

it('creates blocked project when force_save_blocked=true', function () {
    $tenant = Tenant::factory()->withRequisites()->create(['balance_rub' => '1000.00']);
    $user = User::factory()->create(['tenant_id' => $tenant->id]);

    $response = $this->actingAs($user)->postJson('/api/projects', [
        'name' => 'Заблокированный',
        'signal_type' => 'site',
        'signal_identifier' => 'force-blocked.ru',
        'daily_limit_target' => 30,
        'regions' => [],
        'delivery_days_mask' => 127,
        'force_save_blocked' => true,
    ]);

    $response->assertCreated();
    $project = Project::where('signal_identifier', 'force-blocked.ru')->first();
    expect($project)->not->toBeNull();
    expect($project->preflight_blocked_at)->not->toBeNull();
});

it('creates normally when within balance', function () {
    // 2000₽ / 50₽ = 40 лидов capacity; daily_limit_target=30 — passes.
    $tenant = Tenant::factory()->withRequisites()->create(['balance_rub' => '2000.00']);
    $user = User::factory()->create(['tenant_id' => $tenant->id]);

    $response = $this->actingAs($user)->postJson('/api/projects', [
        'name' => 'Норма',
        'signal_type' => 'site',
        'signal_identifier' => 'ok-balance.ru',
        'daily_limit_target' => 30,
        'regions' => [],
        'delivery_days_mask' => 127,
    ]);

    $response->assertCreated();
    $project = Project::where('signal_identifier', 'ok-balance.ru')->first();
    expect($project->preflight_blocked_at)->toBeNull();
});

it('does not order blocked project at supplier on create', function () {
    // Баланс не тянет лимит → клиент продавил force_save_blocked → проект помечен
    // preflight_blocked_at. Такой проект НЕ должен уезжать заказом к поставщику
    // (зеркалит фильтр sweep-джоба ->whereNull('preflight_blocked_at')).
    $tenant = Tenant::factory()->withRequisites()->create(['balance_rub' => '1000.00']);
    $user = User::factory()->create(['tenant_id' => $tenant->id]);

    $this->actingAs($user)->postJson('/api/projects', [
        'name' => 'Блок-без-заказа',
        'signal_type' => 'site',
        'signal_identifier' => 'blocked-no-order.ru',
        'daily_limit_target' => 30,
        'regions' => [],
        'delivery_days_mask' => 127,
        'force_save_blocked' => true,
    ])->assertCreated();

    Queue::assertNotPushed(SyncSupplierProjectJob::class);
});

it('orders unblocked project at supplier on create', function () {
    // Баланс тянет лимит → проект не заблокирован → заказ к поставщику уходит.
    $tenant = Tenant::factory()->withRequisites()->create(['balance_rub' => '2000.00']);
    $user = User::factory()->create(['tenant_id' => $tenant->id]);

    $this->actingAs($user)->postJson('/api/projects', [
        'name' => 'Норма-с-заказом',
        'signal_type' => 'site',
        'signal_identifier' => 'ok-order.ru',
        'daily_limit_target' => 30,
        'regions' => [],
        'delivery_days_mask' => 127,
    ])->assertCreated();

    Queue::assertPushed(SyncSupplierProjectJob::class);
});

it('returns 409 on update when increased limit overloads balance', function () {
    // существующий проект на 15 лидов, всё ок (capacity 20).
    $tenant = Tenant::factory()->withRequisites()->create(['balance_rub' => '1000.00']);
    $user = User::factory()->create(['tenant_id' => $tenant->id]);
    $project = Project::factory()->for($tenant)->create([
        'is_active' => true,
        'daily_limit_target' => 15,
    ]);

    // UPDATE до 30 → suma 30 > capacity 20 → 409.
    $response = $this->actingAs($user)->patchJson("/api/projects/{$project->id}", [
        'daily_limit_target' => 30,
    ]);

    $response->assertStatus(409);
    $response->assertJsonPath('error', 'balance_insufficient');
    expect($project->fresh()->daily_limit_target)->toBe(15); // не изменилось
});
