<?php

namespace Tests\Feature;

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

class AdminPlatformOrderToolFormsShouldCarryRenewalMissingSubscriptionFilterTest 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 assertFilteredToolFormsCarryRenewalMissingSubscription(string $html, string $method, string $action): void
    {
        $pattern = sprintf(
            '/<form[^>]*method="%s"[^>]*action="%s"[^>]*>(.*?)<\\/form>/si',
            preg_quote($method, '/'),
            preg_quote($action, '/')
        );

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

        $checked = 0;
        foreach ($matches[0] as $formHtml) {
            // 仅校验 scope=filtered 的工具表单：scope=all 属于“全量动作”，不应承载筛选字段。
            if (! str_contains($formHtml, 'name="scope" value="filtered"')) {
                continue;
            }

            $checked++;
            $this->assertStringContainsString('name="renewal_missing_subscription"', $formHtml, '表单未透传 renewal_missing_subscription：' . $action);
            $this->assertStringContainsString('value="1"', $formHtml, '表单 renewal_missing_subscription 值应为 1：' . $action);
        }

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

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

        $page = $this->get('/admin/platform-orders?renewal_missing_subscription=1');
        $page->assertOk();

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

        // export 没有 scope=filtered/all 的概念，本质上就是“当前筛选集合导出”，因此直接断言即可。
        $this->assertStringContainsString('name="renewal_missing_subscription"', $html);
        $this->assertStringContainsString('action="/admin/platform-orders/export"', $html);

        // 仅校验 scope=filtered 的工具表单透传（scope=all 属于全量动作，不承载筛选字段）。
        $this->assertFilteredToolFormsCarryRenewalMissingSubscription($html, 'post', '/admin/platform-orders/batch-activate-subscriptions');
        $this->assertFilteredToolFormsCarryRenewalMissingSubscription($html, 'post', '/admin/platform-orders/batch-mark-paid-and-activate');
        $this->assertFilteredToolFormsCarryRenewalMissingSubscription($html, 'post', '/admin/platform-orders/batch-mark-activated');
        $this->assertFilteredToolFormsCarryRenewalMissingSubscription($html, 'post', '/admin/platform-orders/clear-sync-errors');
        $this->assertFilteredToolFormsCarryRenewalMissingSubscription($html, 'post', '/admin/platform-orders/clear-bmpa-errors');
    }
}
