<?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 AdminPlatformLeadIndexPaidNoReceiptGovernanceLinkShouldUseLeadIndexSelfBackTest 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_paid_no_receipt_governance_link_should_use_lead_index_self_as_back(): void
    {
        $this->loginAsPlatformAdmin();

        $plan = Plan::query()->create([
            'code' => 'lead_index_paid_no_receipt_back_plan',
            'name' => '线索页已付无回执入口 back 口径测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 99,
            'list_price' => 99,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $lead = PlatformLead::query()->create([
            'name' => '线索已付无回执回跳测试',
            'mobile' => '13900000009',
            'email' => 'lead-paid-no-receipt-back@example.com',
            'company' => '线索治理回跳测试公司',
            'plan_id' => $plan->id,
            'source' => 'web',
            'status' => 'new',
        ]);

        $res = $this->get('/admin/platform-leads?back=' . urlencode('/admin/platform-orders?payment_status=paid'));
        $res->assertOk();

        $html = (string) $res->getContent();
        $matched = preg_match('/<a[^>]+href="([^"]+)"[^>]*>\s*已付无回执\s*<\/a>/u', $html, $m);
        $this->assertSame(1, $matched, '未找到线索页“已付无回执”入口');

        $href = html_entity_decode($m[1] ?? '');
        $expectedUrl = '/admin/platform-orders?' . Arr::query([
            'lead_id' => $lead->id,
            'payment_status' => 'paid',
            'receipt_status' => 'none',
            'back' => '/admin/platform-leads',
        ]);

        $this->assertSame($expectedUrl, $href);
        $this->assertStringNotContainsString(urlencode('/admin/platform-orders?payment_status=paid'), $href);
    }
}
