<?php

namespace Tests\Feature;

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

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

        $back = '/admin/site-subscriptions?status=activated&keyword=test';

        $res = $this->get('/admin/platform-orders?back=' . urlencode($back));
        $res->assertOk();

        $html = $res->getContent();

        // 选一个稳定存在的 fullUrlWithQuery 链接：支付状态=已支付
        // 断言它仍然携带 back（且 back 原始值中包含 &，因此最终 href 中应包含 back=%2F...%26...）
        preg_match_all('/href="([^"]+)"/', $html, $matches);
        $hrefs = $matches[1] ?? [];

        $found = false;
        foreach ($hrefs as $u) {
            if (!str_contains($u, '/admin/platform-orders')) {
                continue;
            }
            if (!str_contains($u, 'payment_status=paid')) {
                continue;
            }

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

            if (($q['payment_status'] ?? null) === 'paid' && ($q['back'] ?? null) === $back) {
                $found = true;
                break;
            }
        }

        $this->assertTrue($found, '未找到携带 back 的 payment_status=paid 链接（fullUrlWithQuery 可能丢失 back）');
    }
}
