<?php

namespace Tests\Feature;

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

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

        $res = $this->get('/admin/site-subscriptions?merchant_id=2&plan_id=3&back=%2Fadmin%2Fplatform-orders&keyword=abc&page=9&status=pending&expiry=expiring_7d');
        $res->assertOk();

        $html = (string) $res->getContent();
        preg_match_all('/href="([^"]+)"/', $html, $m);
        $hrefs = $m[1] ?? [];
        $this->assertGreaterThan(0, count($hrefs));

        $expiredLinks = array_values(array_filter($hrefs, fn ($u) => str_contains($u, '/admin/site-subscriptions') && str_contains($u, 'expiry=expired')));
        $this->assertGreaterThanOrEqual(1, count($expiredLinks));

        $expiring7dLinks = array_values(array_filter($hrefs, fn ($u) => str_contains($u, '/admin/site-subscriptions') && str_contains($u, 'expiry=expiring_7d')));
        $this->assertGreaterThanOrEqual(1, count($expiring7dLinks));

        foreach ([$expiredLinks[0], $expiring7dLinks[0]] as $url) {
            $parts = parse_url($url);
            parse_str($parts['query'] ?? '', $q);

            // 保留上下文：merchant/plan/keyword/back
            $this->assertSame('2', (string) ($q['merchant_id'] ?? ''));
            $this->assertSame('3', (string) ($q['plan_id'] ?? ''));
            $this->assertSame('abc', (string) ($q['keyword'] ?? ''));
            $this->assertSame('/admin/platform-orders', (string) ($q['back'] ?? ''));

            // 不应继承 status/page
            $this->assertArrayNotHasKey('status', $q);
            $this->assertArrayNotHasKey('page', $q);
        }

        // 仅要求“到期治理”两个入口本身不要出现 &amp;（分页等其它区域可能会由 Laravel 自身输出 &amp;，不在本测试范围）。
        $this->assertStringNotContainsString('&amp;', $expiredLinks[0]);
        $this->assertStringNotContainsString('&amp;', $expiring7dLinks[0]);
    }
}
