<?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('свой период (date_from/date_to) учитывает только пополнения внутри диапазона', function () {
    $t = DB::table('tenants')->insertGetId([
        'subdomain' => 'acme', 'organization_name' => 'Acme', 'contact_email' => 'a@acme.ru',
        'status' => 'active', 'is_trial' => false, 'balance_rub' => 0, 'balance_leads' => 0,
        'chargeback_unrecovered_rub' => 0, 'created_at' => now()->subDays(100), 'updated_at' => now(),
    ]);
    // даты в текущем месяце — партиции balance_transactions существуют только на свежие месяцы
    $in = now()->startOfMonth()->addDays(4)->setTime(12, 0);
    $out = now()->startOfMonth()->addDays(20)->setTime(12, 0);
    DB::table('balance_transactions')->insert([
        ['tenant_id' => $t, 'type' => 'topup', 'amount_rub' => 5000, 'created_at' => $in],
        ['tenant_id' => $t, 'type' => 'topup', 'amount_rub' => 9000, 'created_at' => $out],
    ]);

    $from = now()->startOfMonth()->addDays(2)->toDateString();
    $to = now()->startOfMonth()->addDays(10)->toDateString();
    $res = $this->getJson("/api/admin/dashboard/finance?date_from={$from}&date_to={$to}");

    $res->assertOk();
    expect($res->json('kpi.topups_rub'))->toBe('5000'); // только пополнение внутри диапазона
});

it('свой период имеет приоритет над preset', function () {
    $res = $this->getJson('/api/admin/dashboard?period=7d&date_from=2026-06-01&date_to=2026-06-15');
    $res->assertOk();
    expect($res->json('date_from'))->toBe('2026-06-01');
    expect($res->json('date_to'))->toBe('2026-06-15');
});
