<?php

declare(strict_types=1);

use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;

uses(DatabaseTransactions::class);

beforeEach(function () {
    DB::table('balance_transactions')->delete();
    DB::table('tenants')->delete();
});

it('GET /api/admin/dashboard/finance returns KPIs + attention + top tables', function () {
    $neg = DB::table('tenants')->insertGetId([
        'subdomain' => 'neg', 'organization_name' => 'Negative', 'contact_email' => 'n@x.ru',
        'status' => 'active', 'is_trial' => false, 'balance_rub' => -100, 'balance_leads' => 0,
        'chargeback_unrecovered_rub' => 0, 'created_at' => now(), 'updated_at' => now(),
    ]);
    DB::table('balance_transactions')->insert([
        'tenant_id' => $neg, 'type' => 'topup', 'amount_rub' => 5000, 'created_at' => now(),
    ]);

    $res = $this->getJson('/api/admin/dashboard/finance?period=30d');

    $res->assertOk();
    $res->assertJsonStructure([
        'kpi' => ['topups_rub', 'charges_rub', 'net_inflow_rub', 'negative_balance_count'],
        'attention', 'top_by_turnover', 'period',
    ]);
    expect($res->json('kpi.negative_balance_count'))->toBe(1);
    expect(collect($res->json('attention'))->pluck('organization_name'))->toContain('Negative');
    expect(collect($res->json('top_by_turnover'))->pluck('organization_name'))->toContain('Negative');
});
