<?php

namespace Tests\Feature;

use App\Models\Merchant;
use App\Models\PlatformOrder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;

class AdminDashboardBillingWorkbenchShouldIncludeBmpaSuccessQuickLinkTest extends TestCase
{
    use RefreshDatabase;

    protected function loginAsPlatformAdmin(): void
    {
        $this->seed();

        $this->post('/admin/login', [
            'email' => 'platform.admin@demo.local',
            'password' => 'Platform@123456',
        ])->assertRedirect('/admin');
    }

    public function test_dashboard_billing_workbench_should_include_bmpa_success_quick_link(): void
    {
        Cache::flush();

        $this->loginAsPlatformAdmin();

        // 清理 seed 中的订单数据，避免 seed 口径变化影响该用例（仅验证仪表盘是否提供入口与计数渲染）
        PlatformOrder::query()->delete();

        $merchantId = (int) Merchant::query()->value('id');

        // 构造：1 条 BMPA 成功订单（run_id 存在且 error.message 为空）
        PlatformOrder::query()->create([
            'merchant_id' => $merchantId,
            'plan_id' => null,
            'site_subscription_id' => null,
            'created_by_admin_id' => null,
            'order_no' => 'PO_DASH_BMPA_SUCCESS_001',
            'order_type' => 'new_purchase',
            'status' => 'pending',
            'payment_status' => 'unpaid',
            'payable_amount' => 9,
            'paid_amount' => 0,
            'meta' => [
                'batch_mark_paid_and_activate' => [
                    'run_id' => 'BMPA_RUN_SUCCESS_001',
                ],
            ],
        ]);

        Cache::flush();

        $res = $this->get('/admin');
        $res->assertOk();

        // 计数应渲染到按钮文案中
        $res->assertSee('BMPA成功（1）');

        // 链接应携带 back，并且不应出现 &amp;back=（避免回跳断链）
        $res->assertSee('bmpa_success_only=1', false);
        $res->assertSee('back=%2Fadmin', false);
        $res->assertDontSee('&amp;back=', false);
    }
}
