<?php

namespace Tests\Feature;

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

class AdminPlatformOrderIndexScopeAllToolFormsShouldNotCarryFiltersTest extends TestCase
{
    use RefreshDatabase;

    protected function loginAsPlatformAdmin(): void
    {
        $this->seed();

        $this->post('/admin/login', [
            'email' => 'platform.admin@demo.local',
            'password' => 'Platform@123456',
        ])->assertRedirect('/admin');
    }

    protected function assertScopeAllFormDoesNotCarryFilters(string $html, string $action): void
    {
        $pattern = sprintf(
            '/<form[^>]*method="post"[^>]*action="%s"[^>]*>(.*?)<\\/form>/si',
            preg_quote($action, '/')
        );

        $matched = preg_match_all($pattern, $html, $matches);
        $this->assertGreaterThan(0, $matched, '未找到表单：action=' . $action);

        $checked = 0;
        foreach ($matches[0] as $formHtml) {
            if (! str_contains($formHtml, 'name="scope" value="all"')) {
                continue;
            }

            $checked++;

            // Guardrail：scope=all 属于“全量动作”，不应携带当前筛选字段，避免造成“看起来只处理当前筛选”的误导。
            $this->assertStringNotContainsString('name="status"', $formHtml, 'scope=all 表单不应透传 status：' . $action);
            $this->assertStringNotContainsString('name="merchant_id"', $formHtml, 'scope=all 表单不应透传 merchant_id：' . $action);
            $this->assertStringNotContainsString('name="sync_status"', $formHtml, 'scope=all 表单不应透传 sync_status：' . $action);
            $this->assertStringNotContainsString('name="renewal_missing_subscription"', $formHtml, 'scope=all 表单不应透传 renewal_missing_subscription：' . $action);
        }

        $this->assertGreaterThan(0, $checked, '未找到 scope=all 的工具表单：' . $action);
    }

    public function test_platform_orders_scope_all_tool_forms_should_not_carry_filters(): void
    {
        $this->loginAsPlatformAdmin();

        // 构造一个“筛选很复杂”的场景，确保如果页面上误透传筛选字段，测试能命中。
        $res = $this->get('/admin/platform-orders?status=pending&payment_status=paid&merchant_id=1&sync_status=unsynced&renewal_missing_subscription=1');
        $res->assertOk();

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

        $this->assertScopeAllFormDoesNotCarryFilters($html, '/admin/platform-orders/batch-activate-subscriptions');
        $this->assertScopeAllFormDoesNotCarryFilters($html, '/admin/platform-orders/batch-mark-paid-and-activate');
        $this->assertScopeAllFormDoesNotCarryFilters($html, '/admin/platform-orders/batch-mark-activated');
        $this->assertScopeAllFormDoesNotCarryFilters($html, '/admin/platform-orders/clear-sync-errors');
        $this->assertScopeAllFormDoesNotCarryFilters($html, '/admin/platform-orders/clear-bmpa-errors');
    }
}
