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

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

        $plan = Plan::query()->create([
            'code' => 'po_index_sync_failed_link_plan',
            'name' => '平台订单列表 同步失败原因链接优先批次测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'site_subscription_id' => null,
            'created_by_admin_id' => $platformAdminId ?: null,
            'order_no' => 'PO_INDEX_SYNC_FAILED_LINK_0001',
            'order_type' => 'new_purchase',
            'status' => 'activated',
            'payment_status' => 'paid',
            'payable_amount' => 10,
            'paid_amount' => 10,
            'placed_at' => now(),
            'meta' => [
                'subscription_activation_error' => [
                    'message' => 'SYNC_FAILED_KEYWORD_DEMO',
                ],
                'batch_activation' => [
                    'last_result' => [
                        'run_id' => 'BAS_RUN_ID_0001',
                    ],
                ],
            ],
        ]);

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

        $res->assertSee('PO_INDEX_SYNC_FAILED_LINK_0001');

        // 行内“同步失败原因”应优先落到“本批次按原因筛选”（而不是全局原因筛选），减少噪音并提升可执行性
        $res->assertSee('batch_activation_run_id=BAS_RUN_ID_0001', false);
        $res->assertSee('sync_status=failed', false);
        $res->assertSee('sync_error_keyword=SYNC_FAILED_KEYWORD_DEMO', false);
    }
}
