<?php

namespace Tests\Feature;

use App\Models\Admin;
use App\Models\Merchant;
use App\Models\PlatformOrder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class AdminDashboardRecentPlatformOrdersScanlineRefundTraceShouldLinkToAnchorTest 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_recent_platform_orders_scanline_refund_trace_should_link_to_add_refund_receipt_anchor(): void
    {
        $this->loginAsPlatformAdmin();

        // 清理 seed 订单，避免最近订单列表被 seed 污染导致断言不稳定。
        PlatformOrder::query()->delete();

        $merchantId = (int) Merchant::query()->value('id');
        $platformAdminId = (int) Admin::query()->where('email', 'platform.admin@demo.local')->value('id');

        // 构造：已支付订单，有退款轨迹（refund_summary.total_amount > 0），但不触发退款不一致。
        // paid=10, refund=1 => 在 payment_status!=refunded 时，不应命中 isRefundInconsistent。
        $order = PlatformOrder::query()->create([
            'merchant_id' => $merchantId,
            'plan_id' => null,
            'site_subscription_id' => null,
            'created_by_admin_id' => $platformAdminId ?: null,
            'order_no' => 'PO_DASH_SCANLINE_REFUND_TRACE_0001',
            'order_type' => 'new_purchase',
            'status' => 'pending',
            'payment_status' => 'paid',
            'payable_amount' => 10,
            'paid_amount' => 10,
            'placed_at' => now(),
            'paid_at' => now(),
            'meta' => [
                // 明确提供退款轨迹
                'refund_summary' => [
                    'total_amount' => 1,
                    'count' => 1,
                ],
            ],
        ]);

        $this->assertFalse($order->isRefundInconsistent(), '预期测试订单不应命中 isRefundInconsistent()');
        $this->assertGreaterThan(0, (float) $order->refundTotal(), '预期测试订单应存在退款轨迹（refundTotal>0）');

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

        $res->assertSee('PO_DASH_SCANLINE_REFUND_TRACE_0001');

        // 扫描行应显示“退款：有”，并可点击直达 add-refund-receipt 面板（最短治理入口）。
        $res->assertSee('退款：', false);
        $res->assertSee('<strong>有</strong>', false);
        $res->assertSee('#add-refund-receipt', false);
    }
}
