<?php

namespace Tests\Feature;

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

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

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

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

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

        $res = $this->get('/admin/platform-leads');
        $res->assertOk();

        $html = (string) $res->getContent();

        // create renewal url should include merchant_id
        $this->assertStringContainsString('创建续费订单', $html);
        $this->assertStringContainsString('merchant_id=' . $merchant->id, $html);
        $this->assertStringContainsString('plan_id=' . $plan->id, $html);
        $this->assertStringContainsString('require_subscription=1', $html);
        $this->assertStringContainsString('lead_id=' . $lead->id, $html);
    }
}
