<?php

namespace Tests\Feature;

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

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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'po_show_bmpa_find_sub_renewal_no_sub_plan',
            'name' => '订单详情 BMPA 治理引导（续费无订阅）测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 30,
            'list_price' => 30,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $order = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_SHOW_BMPA_FIND_SUB_RENEW_NO_SUB_0001',
            'order_type' => 'renewal',
            'status' => 'pending',
            'payment_status' => 'unpaid',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'payable_amount' => 30,
            'paid_amount' => 0,
            'placed_at' => now(),
            'meta' => [],
        ]);

        $res = $this->get('/admin/platform-orders/' . $order->id);
        $res->assertOk();

        $res->assertSee('BMPA 治理提示', false);
        $res->assertSee('去订阅管理查找订阅', false);

        // 链接应包含 merchant_id/plan_id，并携带 back 回到当前订单详情
        $matched = preg_match('/<a[^>]+href="([^"]+)"[^>]*>\s*去订阅管理查找订阅\s*<\/a>/u', (string) $res->getContent(), $m);
        $this->assertSame(1, $matched, '未找到 BMPA 治理提示中的「去订阅管理查找订阅」链接');

        $url = $m[1] ?? '';
        $parts = parse_url($url);
        parse_str($parts['query'] ?? '', $q);

        $this->assertSame((string) $merchant->id, (string) ($q['merchant_id'] ?? ''));
        $this->assertSame((string) $plan->id, (string) ($q['plan_id'] ?? ''));
        $this->assertSame('/admin/platform-orders/' . $order->id, (string) ($q['back'] ?? ''));
    }
}
