<?php

namespace Tests\Feature;

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

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

        $merchant = Merchant::query()->firstOrFail();

        $plan = Plan::query()->create([
            'code' => 'po_index_sub_lock_rms_plan',
            'name' => '平台订单列表订阅锁定治理入口（续费缺订阅）测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $sub = SiteSubscription::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'status' => 'active',
            'source' => 'manual',
            'subscription_no' => 'SS_SUB_LOCK_RMS_0001',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'amount' => 10,
            'starts_at' => now(),
            'ends_at' => now()->addMonth(),
        ]);

        $res = $this->get('/admin/platform-orders?lead_id=12&merchant_id=' . $merchant->id . '&plan_id=' . $plan->id . '&site_subscription_id=' . $sub->id . '&keyword=abc&page=9&back=%2Fadmin%2Fplans&syncable_only=1');
        $res->assertOk();

        $html = (string) $res->getContent();

        $matched = preg_match('/<a[^>]+href="([^"]+)"[^>]*>\s*查看续费缺订阅（该订阅）\s*<\/a>/u', $html, $m);
        $this->assertSame(1, $matched, '未找到订阅治理入口：查看续费缺订阅（该订阅）');

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

        // 应保留上下文：merchant/plan/subscription/keyword/lead/back
        $this->assertSame('12', (string) ($q['lead_id'] ?? ''));
        $this->assertSame((string) $merchant->id, (string) ($q['merchant_id'] ?? ''));
        $this->assertSame((string) $plan->id, (string) ($q['plan_id'] ?? ''));
        $this->assertSame((string) $sub->id, (string) ($q['site_subscription_id'] ?? ''));
        $this->assertSame('abc', (string) ($q['keyword'] ?? ''));

        // 注意：quick filter 会保留 back（safeBackForLinks），并清空 page
        $this->assertSame('/admin/plans', (string) ($q['back'] ?? ''));

        // 并覆盖 renewal_missing_subscription
        $this->assertSame('1', (string) ($q['renewal_missing_subscription'] ?? ''));

        // 不应继承工具型开关
        $this->assertArrayNotHasKey('syncable_only', $q);
        $this->assertArrayNotHasKey('page', $q);
    }
}
