<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Route;
use Tests\TestCase;

class BackUrlCurrentPathQuickFilterShouldKeepContextAndClearPageTest extends TestCase
{
    use RefreshDatabase;

    public function test_current_path_quick_filter_should_keep_context_and_clear_page(): void
    {
        // 通过一个临时路由把 request()->path()/query() 固定下来，并直接返回 currentPathQuickFilter 的结果
        if (!Route::has('test.backurl.quickfilter')) {
            Route::get('/__test/backurl/quickfilter', function () {
                $safeBack = \App\Support\BackUrl::sanitizeForLinks((string) request()->query('back', ''));

                return response()->json([
                    'url' => \App\Support\BackUrl::currentPathQuickFilter(
                        ['merchant_id', 'plan_id', 'site_subscription_id', 'keyword', 'lead_id', 'created_from', 'created_to'],
                        [
                            'sync_status' => 'failed',
                            'bmpa_failed_only' => null,
                        ],
                        $safeBack
                    ),
                ]);
            })->name('test.backurl.quickfilter');
        }

        $res = $this->get('/__test/backurl/quickfilter?' . http_build_query([
            'merchant_id' => 1,
            'plan_id' => 2,
            'page' => 9,
            'bmpa_failed_only' => 1,
            'sync_status' => 'failed',
            'created_from' => '2026-03-01',
            'created_to' => '2026-03-18',
            'back' => '/admin',
        ]));

        $res->assertOk();
        $data = $res->json();
        $url = (string) ($data['url'] ?? '');

        // 1) page 被清理
        $this->assertStringNotContainsString('page=', $url);

        // 2) 只保留 context keys + overrides + back
        $this->assertStringContainsString('/__test/backurl/quickfilter?', $url);
        $this->assertStringContainsString('merchant_id=1', $url);
        $this->assertStringContainsString('plan_id=2', $url);
        $this->assertStringContainsString('created_from=2026-03-01', $url);
        $this->assertStringContainsString('created_to=2026-03-18', $url);
        $this->assertStringContainsString('sync_status=failed', $url);
        $this->assertStringContainsString('back=%2Fadmin', $url);

        // 3) overrides 清理项生效
        $this->assertStringNotContainsString('bmpa_failed_only=1', $url);
    }
}
