<?php

namespace Tests\Feature;

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

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

        // 快捷筛选应只保留上下文键（back/keyword），不继承 page/status 等其它筛选。
        $res = $this->get('/admin/plans?status=active&billing_cycle=monthly&keyword=abc&page=9&back=%2Fadmin%2Fplatform-orders');
        $res->assertOk();

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

        // 页面渲染正常
        $res->assertSee('快捷筛选', false);

        // 快捷筛选链接不应携带 page=9
        $this->assertStringNotContainsString('page=9', $html);

        // 快捷筛选链接应保留 back（上下文）
        $this->assertStringContainsString('back=%2Fadmin%2Fplatform-orders', $html);

        // 快捷筛选链接应保留 keyword（上下文）
        $this->assertStringContainsString('keyword=abc', $html);

        // 同时不应把当前 status/billing_cycle/page 继承到快捷筛选链接中（避免叠加导致空结果）。
        // 这里定位“启用中(status=active)”的快捷筛选链接做断言（不依赖 query 参数顺序）。
        preg_match_all('/href="([^"]+)"/', $html, $m);
        $hrefs = $m[1] ?? [];

        $found = false;
        foreach ($hrefs as $u) {
            if (!str_starts_with($u, '/admin/plans?')) {
                continue;
            }

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

            if (($q['status'] ?? null) !== 'active') {
                continue;
            }

            $found = true;

            $this->assertSame('abc', $q['keyword'] ?? null);
            $this->assertSame('/admin/platform-orders', $q['back'] ?? null);

            $this->assertArrayNotHasKey('page', $q);
            $this->assertArrayNotHasKey('billing_cycle', $q);
            break;
        }

        $this->assertTrue($found, '未找到 status=active 的快捷筛选链接用于断言');
    }
}
