<?php

namespace Tests\Feature;

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

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

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

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

        // 抓取“近7天到期”链接
        preg_match_all('/href="([^"]+)"/', $html, $m);
        $hrefs = $m[1] ?? [];

        $links = array_values(array_filter($hrefs, fn ($u) => str_contains($u, '近7天到期') === false));
        // 上面这行没意义（文案不在 href），我们直接按 ends_from/ends_to+merchant_id 来筛
        $rangeLinks = array_values(array_filter($hrefs, fn ($u) => str_contains($u, '/admin/site-subscriptions') && str_contains($u, 'ends_from=') && str_contains($u, 'ends_to=') && str_contains($u, 'merchant_id=2') && str_contains($u, 'plan_id=3')));
        $this->assertGreaterThanOrEqual(1, count($rangeLinks));

        $parts = parse_url($rangeLinks[0]);
        parse_str($parts['query'] ?? '', $q);

        $this->assertSame('2', (string) ($q['merchant_id'] ?? ''));
        $this->assertSame('3', (string) ($q['plan_id'] ?? ''));
        $this->assertSame('abc', (string) ($q['keyword'] ?? ''));
        $this->assertSame('pending', (string) ($q['status'] ?? ''));
        $this->assertSame('expired', (string) ($q['expiry'] ?? ''));
        $this->assertSame('/admin/platform-orders', (string) ($q['back'] ?? ''));

        // 应清空分页，避免停留在旧页码导致空结果错觉
        $this->assertArrayNotHasKey('page', $q);

        // ends_from/ends_to 必须存在（具体日期值不在本测试锁死）
        $this->assertArrayHasKey('ends_from', $q);
        $this->assertArrayHasKey('ends_to', $q);
        $this->assertNotSame('', (string) ($q['ends_from'] ?? ''));
        $this->assertNotSame('', (string) ($q['ends_to'] ?? ''));
    }
}
