<?php

namespace Tests\Feature;

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

class AdminDashboardRecentPlatformOrdersFailedHintsSameReasonLinkShouldUseConfigMaxLenTest 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_dashboard_failed_hints_same_reason_link_should_use_config_max_len(): void
    {
        config()->set('saasshop.platform_orders.sync_error_keyword_link_max_len', 5);

        $this->loginAsPlatformAdmin();

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

        // len=5：应生成“同原因集合”链接
        PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => null,
            'site_subscription_id' => null,
            'created_by_admin_id' => $platformAdminId ?: null,
            'order_no' => 'PO_DASH_SYNC_REASON_LEN5',
            'order_type' => 'new_purchase',
            'status' => 'pending',
            'payment_status' => 'paid',
            'payable_amount' => 10,
            'paid_amount' => 10,
            'placed_at' => now(),
            'meta' => [
                'subscription_activation_error' => ['message' => '12345'],
            ],
        ]);

        // len=6：应显示“原因过长”，不生成“同原因集合”链接
        PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => null,
            'site_subscription_id' => null,
            'created_by_admin_id' => $platformAdminId ?: null,
            'order_no' => 'PO_DASH_SYNC_REASON_LEN6',
            'order_type' => 'new_purchase',
            'status' => 'pending',
            'payment_status' => 'paid',
            'payable_amount' => 10,
            'paid_amount' => 10,
            'placed_at' => now(),
            'meta' => [
                'subscription_activation_error' => ['message' => '123456'],
            ],
        ]);

        $res = $this->get('/admin');
        $res->assertOk();

        $res->assertSee('PO_DASH_SYNC_REASON_LEN5');
        $res->assertSee('同原因集合', false);

        $res->assertSee('PO_DASH_SYNC_REASON_LEN6');
        $res->assertSee('原因过长', false);
    }
}
