<?php

namespace Tests\Feature;

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

class AdminSiteSubscriptionIndexQuickFilterLinksKeepContextTest 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();

        $res = $this->get('/admin/site-subscriptions?merchant_id=2&plan_id=3&back=%2Fadmin%2Fplatform-orders&keyword=abc&page=9&status=pending&expiry=expired');
        $res->assertOk();

        $html = (string) $res->getContent();
        preg_match_all('/href="([^"]+)"/', $html, $m);
        $hrefs = $m[1] ?? [];
        $this->assertGreaterThan(0, count($hrefs));

        // 找到“已生效”快捷筛选链接（status=activated）
        $activatedLinks = array_values(array_filter($hrefs, fn ($u) => str_contains($u, '/admin/site-subscriptions') && str_contains($u, 'status=activated')));
        $this->assertGreaterThanOrEqual(1, count($activatedLinks));

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

        // 保留上下文：merchant/plan/back/keyword
        $this->assertSame('2', (string) ($q['merchant_id'] ?? ''));
        $this->assertSame('3', (string) ($q['plan_id'] ?? ''));
        $this->assertSame('/admin/platform-orders', (string) ($q['back'] ?? ''));
        $this->assertSame('abc', (string) ($q['keyword'] ?? ''));

        // 覆盖/清理：status=activated，且不应带 expiry/page
        $this->assertSame('activated', (string) ($q['status'] ?? ''));
        $this->assertArrayNotHasKey('expiry', $q);
        $this->assertArrayNotHasKey('page', $q);

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

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

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

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