<?php

declare(strict_types=1);

use App\Models\LegalEntity;
use App\Models\PaymentGateway;
use App\Models\Tenant;
use App\Models\User;
use App\Services\Billing\Gateway\CreatePaymentResult;
use App\Services\Billing\OnlineTopupService;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;

uses(DatabaseTransactions::class);

function actingTenantUser(): User
{
    $tenant = Tenant::factory()->create(['balance_rub' => '0.00']);

    return User::factory()->create(['tenant_id' => $tenant->id]);
}

it('флаг ВЫКЛ — старое мгновенное зачисление (заглушка)', function () {
    DB::table('system_settings')->updateOrInsert(
        ['key' => 'billing_yookassa_enabled'],
        ['value' => 'false', 'type' => 'bool', 'updated_at' => now()]
    );
    $user = actingTenantUser();

    $resp = $this->actingAs($user)->postJson('/api/billing/topup', ['amount_rub' => 500]);

    $resp->assertCreated()->assertJsonStructure(['transaction', 'balance_rub']);
    expect($resp->json('balance_rub'))->toBe('500.00');
});

it('флаг ВКЛ — возвращает confirmation_url, баланс не меняется до webhook', function () {
    DB::table('system_settings')->updateOrInsert(
        ['key' => 'billing_yookassa_enabled'],
        ['value' => 'true', 'type' => 'bool', 'updated_at' => now()]
    );

    $legalEntity = LegalEntity::create([
        'code' => 'test_le_fork_' . uniqid(), 'name' => 'ООО Тест Форк', 'legal_form' => 'OOO',
        'inn' => '7700000001',
    ]);

    PaymentGateway::create([
        'code' => 'yookassa_fork_' . uniqid(), 'name' => 'ЮKassa', 'driver' => 'yookassa',
        'legal_entity_id' => $legalEntity->id,
        'config' => '', 'is_active' => true, 'accepts_methods' => ['card'],
        'min_amount_rub' => '100.00',
    ]);
    $user = actingTenantUser();

    // OnlineTopupService — final class: мокаем через instance-binding в контейнер.
    $fakeService = new class {
        public function start(mixed ...$args): \App\Services\Billing\Gateway\CreatePaymentResult
        {
            return new \App\Services\Billing\Gateway\CreatePaymentResult('pay_x', 'https://yoomoney.ru/checkout/pay_x');
        }
    };
    app()->instance(OnlineTopupService::class, $fakeService);

    $resp = $this->actingAs($user)->postJson('/api/billing/topup', ['amount_rub' => 500]);

    $resp->assertCreated()->assertJson(['confirmation_url' => 'https://yoomoney.ru/checkout/pay_x']);
    expect($user->fresh()->tenant->balance_rub)->toBe('0.00');
});
