<?php

namespace Tests\Feature;

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

class AdminPlatformOrderShowFailedReasonKeywordMaxLenShouldUseConfigTest 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_platform_order_show_failed_reason_keyword_max_len_should_use_config(): void
    {
        // 将阈值设为 5：len=5 应生成同原因链接，len=6 不生成
        config()->set('saasshop.platform_orders.sync_error_keyword_link_max_len', 5);

        $this->loginAsPlatformAdmin();

        $merchantId = (int) Merchant::query()->value('id');
        $platformAdminId = (int) Admin::query()->where('email', 'platform.admin@demo.local')->value('id');

        $plan = Plan::query()->create([
            'code' => 'show_failed_reason_max_len_plan',
            'name' => '订单详情原因阈值配置测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $okMsg = '12345';
        $longMsg = '123456';

        $order = PlatformOrder::query()->create([
            'merchant_id' => $merchantId,
            'plan_id' => $plan->id,
            'site_subscription_id' => null,
            'created_by_admin_id' => $platformAdminId ?: null,
            'order_no' => 'PO_SHOW_FAILED_REASON_MAX_LEN_0001',
            'order_type' => 'new_purchase',
            'status' => 'pending',
            'payment_status' => 'paid',
            'payable_amount' => 10,
            'paid_amount' => 10,
            'meta' => [
                'subscription_activation_error' => ['message' => $okMsg, 'at' => now()->toDateTimeString()],
                'batch_mark_paid_and_activate_error' => ['message' => $longMsg, 'at' => now()->toDateTimeString()],
            ],
        ]);

        $res = $this->get('/admin/platform-orders/' . $order->id);
        $res->assertOk();

        // 同步失败：len=5 应有同原因链接
        $res->assertSee('查看同原因失败订单', false);
        $res->assertSee('sync_error_keyword=' . $okMsg, false);

        // BMPA：len=6 不应生成 keyword 链接（应出现“原因过长”提示）
        $res->assertSee('原因过长', false);
        $res->assertDontSee('bmpa_error_keyword=' . $longMsg, false);
    }
}
