<?php

namespace Tests\Feature;

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

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

        $merchant = Merchant::query()->firstOrFail();

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

        PlatformLead::query()->create([
            'name' => '李四',
            'mobile' => '13900000000',
            'email' => 'ls@example.com',
            'company' => '示例公司2',
            'source' => 'platform_plans',
            'status' => 'new',
            'plan_id' => $plan->id,
            'meta' => ['merchant_id' => $merchant->id],
        ]);

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

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

        $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 ((string) ($q['merchant_id'] ?? '') === (string) $merchant->id
                && (string) ($q['plan_id'] ?? '') === (string) $plan->id) {
                $found = true;
                break;
            }
        }

        $this->assertTrue($found, '未找到包含 merchant_id 预填的创建订单链接');
    }
}
