<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

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

        // 模拟：当前已筛选站点/套餐/订阅ID/线索，并且带一堆其它筛选（可能互斥），以及 page/back
        $res = $this->get('/admin/platform-orders?lead_id=12&merchant_id=2&plan_id=3&site_subscription_id=4&page=9&back=%2Fadmin%2Fplans&syncable_only=1&reconcile_mismatch=1&refund_inconsistent=1&receipt_status=has');
        $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);

        // 应保留上下文：lead/merchant/plan/subscription/back
        $this->assertSame('12', (string) ($q['lead_id'] ?? ''));
        $this->assertSame('2', (string) ($q['merchant_id'] ?? ''));
        $this->assertSame('3', (string) ($q['plan_id'] ?? ''));
        $this->assertSame('4', (string) ($q['site_subscription_id'] ?? ''));
        $this->assertSame('/admin/plans', (string) ($q['back'] ?? ''));

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

        // 并且：不应携带其它互斥筛选字段，避免叠加导致空结果
        $this->assertArrayNotHasKey('page', $q);
        $this->assertArrayNotHasKey('syncable_only', $q);
        $this->assertArrayNotHasKey('reconcile_mismatch', $q);
        $this->assertArrayNotHasKey('refund_inconsistent', $q);
        $this->assertArrayNotHasKey('receipt_status', $q);
    }
}
