<?php

/**
 * 文件功能：后台积分流水统计页面测试
 *
 * 覆盖后台统计页的来源聚合与净流通量口径。
 */

namespace Tests\Feature\Feature;

use App\Enums\CurrencySource;
use App\Models\Sysparam;
use App\Models\User;
use App\Models\UserCurrencyLog;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;

/**
 * 类功能：验证后台积分流水统计页能正确汇总指定日期数据。
 */
class AdminCurrencyStatsControllerTest extends TestCase
{
    use RefreshDatabase;

    /**
     * 验证后台积分流水统计页会返回指定日期的来源统计与净流通数据。
     */
    public function test_admin_can_view_currency_stats_summary_for_selected_date(): void
    {
        Cache::flush();
        Sysparam::updateOrCreate(['alias' => 'superlevel'], ['body' => '100']);

        $admin = User::factory()->create(['user_level' => 100]);
        $date = '2026-04-26';

        UserCurrencyLog::query()->create([
            'user_id' => $admin->id,
            'username' => $admin->username,
            'currency' => 'gold',
            'amount' => 120,
            'balance_after' => 120,
            'source' => CurrencySource::SIGN_IN->value,
            'remark' => '签到奖励',
            'created_at' => "{$date} 10:00:00",
        ]);

        UserCurrencyLog::query()->create([
            'user_id' => $admin->id,
            'username' => $admin->username,
            'currency' => 'gold',
            'amount' => -20,
            'balance_after' => 100,
            'source' => CurrencySource::FISHING_COST->value,
            'remark' => '钓鱼消耗',
            'created_at' => "{$date} 11:00:00",
        ]);

        UserCurrencyLog::query()->create([
            'user_id' => $admin->id,
            'username' => $admin->username,
            'currency' => 'exp',
            'amount' => 80,
            'balance_after' => 80,
            'source' => CurrencySource::AUTO_SAVE->value,
            'remark' => '自动存点',
            'created_at' => "{$date} 12:00:00",
        ]);

        $response = $this->actingAs($admin)->get(route('admin.currency-stats.index', ['date' => $date]));

        $response->assertOk();
        $response->assertViewIs('admin.currency-stats.index');
        $response->assertViewHas('date', $date);
        $response->assertViewHas('netFlow', [
            'exp' => ['in' => 80, 'out' => 0, 'net' => 80],
            'gold' => ['in' => 120, 'out' => 20, 'net' => 100],
            'charm' => ['in' => 0, 'out' => 0, 'net' => 0],
        ]);

        $statsByType = $response->viewData('statsByType');

        $this->assertSame(120, (int) $statsByType['gold'][CurrencySource::SIGN_IN->value]->total_amount);
        $this->assertSame(80, (int) $statsByType['exp'][CurrencySource::AUTO_SAVE->value]->total_amount);
    }
}
