<?php

namespace Tests\Feature;

use App\Models\Plan;
use App\Models\PlatformLead;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Arr;
use Tests\TestCase;

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

        $plan = Plan::query()->create([
            'code' => 'lead_order_plan',
            'name' => '线索转订单测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $lead = PlatformLead::query()->create([
            'name' => '张三',
            'mobile' => '13800000000',
            'email' => 'zs@example.com',
            'company' => '示例公司',
            'source' => 'platform_plans',
            'status' => 'new',
            'plan_id' => $plan->id,
            'meta' => ['from' => 'test'],
        ]);

        $currentUrl = '/admin/platform-leads?' . Arr::query([
            'status' => 'new',
            'keyword' => '张',
        ]);

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

        $selfWithoutBack = '/admin/platform-leads?' . Arr::query([
            'status' => 'new',
            'keyword' => '张',
        ]);

        $html = $res->getContent();

        preg_match_all('/href="([^"]+)"/', $html, $matches);
        $hrefs = $matches[1] ?? [];

        $createUrls = array_values(array_filter($hrefs, fn ($u) => str_contains($u, '/admin/platform-orders/create?')));
        $this->assertNotEmpty($createUrls, '未找到从线索创建订单的链接');

        $found = false;
        foreach ($createUrls as $u) {
            $parts = parse_url($u);
            parse_str($parts['query'] ?? '', $q);

            if (($q['order_type'] ?? '') === 'new_purchase'
                && (string) ($q['plan_id'] ?? '') === (string) $plan->id
                && (string) ($q['back'] ?? '') === $selfWithoutBack
                && str_contains((string) ($q['remark'] ?? ''), '线索#' . $lead->id)
                && str_contains((string) ($q['remark'] ?? ''), '张三')) {
                $found = true;
                break;
            }
        }

        $this->assertTrue($found, '未找到包含 plan_id/back/remark 预填的创建订单链接');
        $res->assertSee('创建订单', false);

        // 防 back 嵌套（URL 不应出现 back%3D）
        $res->assertDontSee('back%3D', false);
    }
}
