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

        $merchant = Merchant::query()->firstOrFail();

        $plan = Plan::query()->create([
            'code' => 'compact_view_sync_reason_test',
            '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,
            'order_no' => 'PO_COMPACT_SYNC_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' => 'SIMULATED_SYNC_ERROR: remote api failed',
                    'at' => now()->toDateTimeString(),
                ],
                'batch_mark_paid_and_activate_error' => [
                    'message' => 'SIMULATED_BMPA_ERROR: validation failed',
                    'at' => now()->toDateTimeString(),
                ],
            ],
        ]);

        // 默认精简视图：应显示原因（full 视图仍由“失败原因”列承载）
        $this->get('/admin/platform-orders')
            ->assertOk()
            ->assertSee('<span class="row-warn-prefix">原因</span>', false)
            ->assertSee('SIMULATED_SYNC_ERROR', false)
            ->assertSee('<span class="row-warn-prefix">BMPA</span>', false)
            ->assertSee('SIMULATED_BMPA_ERROR', false);

        // full 视图：不强制在该单元格重复显示（避免信息过载），这里确保不出现 compact 的前缀文案
        $this->get('/admin/platform-orders?view=full')
            ->assertOk()
            ->assertDontSee('原因：SIMULATED_SYNC_ERROR', false)
            ->assertDontSee('BMPA：SIMULATED_BMPA_ERROR', false);
    }
}
