<?php

namespace Tests\Feature;

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

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

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

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

        $lead = PlatformLead::query()->create([
            'name' => '查看订单线索',
            'mobile' => '13800000004',
            'email' => 'lead4@example.com',
            'company' => '查看订单公司',
            'source' => 'test',
            'status' => 'new',
            'plan_id' => $plan->id,
            'meta' => ['from' => 'test'],
        ]);

        // 关联订单（通过 meta.platform_lead_id）
        PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'site_subscription_id' => null,
            'created_by_admin_id' => 1,
            'order_no' => 'PO_LEAD_VIEW_0001',
            'order_type' => 'new_purchase',
            'status' => 'pending',
            'payment_status' => 'unpaid',
            'payment_channel' => null,
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'list_amount' => 10,
            'discount_amount' => 0,
            'payable_amount' => 10,
            'paid_amount' => 0,
            'placed_at' => now(),
            'plan_snapshot' => ['plan_id' => $plan->id],
            'meta' => ['platform_lead_id' => $lead->id],
            'remark' => 'from lead',
        ]);

        $res = $this->get('/admin/platform-leads?' . Arr::query(['status' => 'new']));
        $res->assertOk();

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

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

        $viewUrls = array_values(array_filter($hrefs, fn ($u) => str_contains($u, '/admin/platform-orders?')));
        $this->assertNotEmpty($viewUrls, '未找到查看订单链接');

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

            if ((string) ($q['lead_id'] ?? '') === (string) $lead->id
                && (string) ($q['back'] ?? '') === $selfWithoutBack) {
                $found = true;
                break;
            }
        }
        $this->assertTrue($found, '未找到包含 lead_id/back 的查看订单链接');

        // 平台订单列表支持按 lead_id 过滤，并能看到对应订单号
        $ordersPage = $this->get('/admin/platform-orders?' . Arr::query(['lead_id' => $lead->id]));
        $ordersPage->assertOk();
        $ordersPage->assertSee('PO_LEAD_VIEW_0001');
    }
}
