<?php

namespace Tests\Feature;

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

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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'sync_failed_reason_top5_url_encode_test',
            'name' => '同步失败原因URL编码测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $reason = 'A&B=1 中文';

        PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_SYNC_FAILED_REASON_ENCODE_0001',
            'order_type' => 'new_purchase',
            'status' => 'activated',
            'payment_status' => 'paid',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'payable_amount' => 10,
            'paid_amount' => 10,
            'placed_at' => now(),
            'paid_at' => now(),
            'activated_at' => now(),
            'meta' => [
                'subscription_activation_error' => [
                    'message' => $reason,
                    'at' => now()->toDateTimeString(),
                    'admin_id' => 1,
                ],
            ],
        ]);

        // RFC3986 编码：& -> %26，= -> %3D，空格 -> %20
        $encoded = 'A%26B%3D1%20%E4%B8%AD%E6%96%87';

        $page = $this->get('/admin/platform-orders');
        $page->assertOk();

        $page->assertSee('sync_status=failed', false);
        $page->assertSee('sync_error_keyword=' . $encoded, false);

        // retry link 也应包含同一编码，并包含 syncable_only=1
        $page->assertSee('切到可同步重试', false);
        $page->assertSee('syncable_only=1', false);
        $page->assertSee('sync_error_keyword=' . $encoded, false);
    }
}
