<?php

namespace Tests\Feature;

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

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

        // 模拟：当前已筛选站点/套餐/订阅ID，并且带一堆其它筛选（可能互斥），以及 page/back
        $res = $this->get('/admin/platform-orders?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();

        preg_match_all('/href="([^"]+)"/', $html, $m);
        $hrefs = $m[1] ?? [];

        // 找到“待支付”的快捷筛选链接：payment_status=unpaid 且不包含 status=pending（避免匹配到“可BMPA处理”）
        $unpaidLinks = array_values(array_filter($hrefs, function ($u) {
            return str_contains($u, '/admin/platform-orders')
                && str_contains($u, 'payment_status=unpaid')
                && !str_contains($u, 'status=pending');
        }));

        $this->assertGreaterThanOrEqual(1, count($unpaidLinks));

        $parts = parse_url($unpaidLinks[0]);
        parse_str($parts['query'] ?? '', $q);

        // 应保留上下文：merchant/plan/subscription/back，并覆盖 payment_status
        $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'] ?? ''));
        $this->assertSame('unpaid', (string) ($q['payment_status'] ?? ''));

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

        // “全部”应清空筛选，仅保留 back
        $allLinks = array_values(array_filter($hrefs, function ($u) {
            if (!str_starts_with($u, '/admin/platform-orders')) {
                return false;
            }

            $p = parse_url($u);
            parse_str($p['query'] ?? '', $q2);

            return (($q2['back'] ?? null) === '/admin/plans') && (count($q2) === 1);
        }));

        $this->assertGreaterThanOrEqual(1, count($allLinks));
    }
}
