<?php

namespace Tests\Feature;

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

class AdminDashboardBillingWorkbenchShouldIncludeBmpaFailedAndNoReceiptQuickLinksTest 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_failed_and_no_receipt_quick_links(): void
    {
        Cache::flush();

        $this->loginAsPlatformAdmin();

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

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

        // 构造：1) BMPA 失败订单（meta.batch_mark_paid_and_activate_error.message 存在）
        // 2) 已支付但无回执证据订单（payment_status=paid 且 payment_summary/payment_receipts 都为空）
        PlatformOrder::query()->create([
            'merchant_id' => $merchantId,
            'plan_id' => null,
            'site_subscription_id' => null,
            'created_by_admin_id' => null,
            'order_no' => 'PO_DASH_BMPA_FAILED_001',
            'order_type' => 'new_purchase',
            'status' => 'pending',
            'payment_status' => 'unpaid',
            'payable_amount' => 9,
            'paid_amount' => 0,
            'meta' => [
                'batch_mark_paid_and_activate_error' => [
                    'message' => 'bmpa failed',
                ],
            ],
        ]);

        PlatformOrder::query()->create([
            'merchant_id' => $merchantId,
            'plan_id' => null,
            'site_subscription_id' => null,
            'created_by_admin_id' => null,
            'order_no' => 'PO_DASH_PAID_NO_RECEIPT_001',
            'order_type' => 'new_purchase',
            'status' => 'pending',
            'payment_status' => 'paid',
            'payable_amount' => 9,
            'paid_amount' => 9,
            'meta' => [],
        ]);

        Cache::flush();

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

        // 计数应渲染到按钮文案中
        $res->assertSee('BMPA失败（1）');
        $res->assertSee('已付无回执（1）');

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