<?php

namespace Tests\Feature;

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

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

        $plan = Plan::query()->create([
            'code' => 'plan_index_paid_no_receipt_back',
            'name' => '套餐页已付无回执回跳测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 88,
            'list_price' => 88,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

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

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

        $targetHref = null;
        foreach ($hrefs as $candidate) {
            if (! str_contains($candidate, '/admin/platform-orders?')) {
                continue;
            }

            $parts = parse_url($candidate);
            parse_str($parts['query'] ?? '', $q);

            if ((string) ($q['plan_id'] ?? '') !== (string) $plan->id) {
                continue;
            }

            if ((string) ($q['payment_status'] ?? '') !== 'paid') {
                continue;
            }

            if ((string) ($q['receipt_status'] ?? '') !== 'none') {
                continue;
            }

            $targetHref = $candidate;
            break;
        }

        $this->assertNotNull($targetHref, '未找到套餐页目标“已付无回执”入口');

        $expectedUrl = '/admin/platform-orders?' . Arr::query([
            'plan_id' => $plan->id,
            'payment_status' => 'paid',
            'receipt_status' => 'none',
            'back' => '/admin/plans',
        ]);

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