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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'sync_failed_reason_top5_truncate_keep_link_test',
            'name' => '同步失败原因截断与链接一致性测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $reason = '这是一个很长很长的失败原因，用于测试页面展示会截断但链接必须包含完整原因以确保筛选可复现_1234567890_ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $shown = mb_substr($reason, 0, 60);

        PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_SYNC_FAILED_REASON_TRUNC_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,
                ],
            ],
        ]);

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

        // 展示应包含截断文本
        $page->assertSee($shown);

        // 链接中应包含完整 reason 的 URL 编码
        $encoded = rawurlencode($reason);
        $page->assertSee('sync_error_keyword=' . $encoded, false);
    }
}
