<?php

namespace Tests\Feature;

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

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

        $currentUrl = '/admin/platform-orders?' . Arr::query([
            'lead_id' => 12,
            'payment_status' => 'paid',
            'back' => '/admin/platform-leads',
        ]);

        $res = $this->get($currentUrl);
        $res->assertOk();

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

        $createLinks = array_values(array_filter($hrefs, fn ($u) => str_contains($u, '/admin/platform-orders/create?')));
        $this->assertNotEmpty($createLinks, '未找到“新建平台订单”链接');

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

        $this->assertSame('12', (string) ($q['lead_id'] ?? ''));
    }
}
