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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'sync_failed_reason_long_reason_no_link_test',
            'name' => '同步失败原因过长不渲染链接测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $reason = str_repeat('很长的失败原因', 30); // > 200 chars
        $shown = mb_substr($reason, 0, 60);

        PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_SYNC_FAILED_LONG_REASON_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);
        $page->assertSee('原因过长，请复制到筛选框');

        // 不应渲染 sync_error_keyword= 的链接（避免 URL 过长/特殊字符问题）
        $page->assertDontSee('sync_error_keyword=', false);

        // 仍应给一个“进入同步失败集合”的入口
        $page->assertSee('进入同步失败集合');
        $page->assertSee('sync_status=failed', false);
    }
}
