<?php

namespace Tests\Feature;

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

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

        $merchant = Merchant::query()->create([
            'name' => '站点已付无回执回跳测试站点',
            'slug' => 'merchant-paid-no-receipt-back',
            'plan' => 'pro',
            'status' => 'active',
            'contact_name' => '李四',
            'contact_phone' => '13800138001',
            'contact_email' => 'merchant-paid-no-receipt-back@example.com',
        ]);

        $res = $this->get('/admin/merchants?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['merchant_id'] ?? '') !== (string) $merchant->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([
            'merchant_id' => $merchant->id,
            'payment_status' => 'paid',
            'receipt_status' => 'none',
            'back' => '/admin/merchants',
        ]);

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