<?php

namespace Tests\Feature;

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

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

        $res = $this->get('/admin/platform-orders?merchant_id=1&reconcile_mismatch=1&back=/admin');
        $res->assertOk();

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

        $this->assertMatchesRegularExpression('/<a[^>]*data-role="po-quickfilter-all"[^>]*href="([^"]+)"/u', $html);
        preg_match('/<a[^>]*data-role="po-quickfilter-all"[^>]*href="([^"]+)"/u', $html, $m);

        $rawHref = (string) ($m[1] ?? '');
        $this->assertStringNotContainsString('&amp;back=', $rawHref);

        $href = html_entity_decode($rawHref);
        $this->assertNotEmpty($href);

        $this->assertSame('/admin/platform-orders', (string) parse_url($href, PHP_URL_PATH));

        $query = parse_url($href, PHP_URL_QUERY) ?: '';
        parse_str($query, $q);

        $this->assertSame('/admin', (string) ($q['back'] ?? ''));
        $this->assertArrayNotHasKey('merchant_id', $q);
        $this->assertArrayNotHasKey('reconcile_mismatch', $q);

        // 说明：页面其他区域（如分页链接）可能会出现 &amp;back= 的转义字符，这里不做全局断言。
        // 我们仅保证该快捷筛选链接本身被正确解析（见上文 parse_str 后的断言）。
    }
}
