<?php

namespace Tests\Feature;

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

class AdminSiteSubscriptionShowFailedReasonTop3KeywordLinkMaxLenShouldUseConfigTest 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_site_subscription_show_failed_reason_top3_keyword_link_max_len_should_use_config(): void
    {
        // 将阈值设为 5：len=5 应生成 keyword 链接；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' => 'sub_show_failed_reason_len_plan',
            'name' => '订阅详情原因阈值配置测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $subscription = SiteSubscription::query()->create([
            'merchant_id' => $merchantId,
            'plan_id' => $plan->id,
            'status' => 'active',
            'source' => 'manual',
            'subscription_no' => 'SS_LEN_CFG_0001',
            'plan_name' => $plan->name,
            'billing_cycle' => 'monthly',
            'period_months' => 1,
            'amount' => 10,
            'starts_at' => now(),
            'ends_at' => now()->addMonth(),
            'meta' => [],
        ]);

        // 注意：失败原因 Top3 来自关联平台订单的 meta 聚合，不读 subscription.meta
        \App\Models\PlatformOrder::query()->create([
            'merchant_id' => $merchantId,
            'plan_id' => $plan->id,
            'site_subscription_id' => $subscription->id,
            'created_by_admin_id' => $platformAdminId ?: null,
            'order_no' => 'PO_SUB_FAIL_REASON_LEN5_0001',
            'order_type' => 'renewal',
            'status' => 'pending',
            'payment_status' => 'paid',
            'payable_amount' => 10,
            'paid_amount' => 10,
            'placed_at' => now(),
            'meta' => [
                'subscription_activation_error' => ['message' => '12345'],
                'batch_mark_paid_and_activate_error' => ['message' => '12345'],
            ],
        ]);

        \App\Models\PlatformOrder::query()->create([
            'merchant_id' => $merchantId,
            'plan_id' => $plan->id,
            'site_subscription_id' => $subscription->id,
            'created_by_admin_id' => $platformAdminId ?: null,
            'order_no' => 'PO_SUB_FAIL_REASON_LEN6_0001',
            'order_type' => 'renewal',
            'status' => 'pending',
            'payment_status' => 'paid',
            'payable_amount' => 10,
            'paid_amount' => 10,
            'placed_at' => now(),
            'meta' => [
                'subscription_activation_error' => ['message' => '123456'],
                'batch_mark_paid_and_activate_error' => ['message' => '123456'],
            ],
        ]);

        $res = $this->get('/admin/site-subscriptions/' . $subscription->id);
        $res->assertOk();

        // len=5 应生成链接
        $res->assertSee('bmpa_error_keyword=12345', false);
        $res->assertSee('sync_error_keyword=12345', false);

        // len=6 不应生成链接（页面仍会展示 reason 文本）
        $res->assertDontSee('bmpa_error_keyword=123456', false);
        $res->assertDontSee('sync_error_keyword=123456', false);

        // 且会出现“原因过长”提示
        $res->assertSee('原因过长', false);
    }
}
