<?php

namespace Tests\Feature;

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

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

        $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');
        $res->assertOk();

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

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

        // 找到“待支付”的快捷筛选链接：payment_status=unpaid
        $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);

        // 应保留 lead_id 上下文
        $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'] ?? ''));

        // 并且不应携带 page/syncable_only
        $this->assertArrayNotHasKey('page', $q);
        $this->assertArrayNotHasKey('syncable_only', $q);
    }
}
