<?php

namespace Tests\Feature;

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

class AdminDashboardRecentPlatformOrdersShouldShowSyncFailedAndBmpaFailedHintsTest 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_recent_platform_orders_should_show_sync_failed_and_bmpa_failed_hints(): void
    {
        $this->loginAsPlatformAdmin();

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

        PlatformOrder::query()->create([
            'merchant_id' => $merchantId,
            'plan_id' => null,
            'site_subscription_id' => null,
            'created_by_admin_id' => $platformAdminId ?: null,
            'order_no' => 'PO_DASH_SYNC_FAILED_0001',
            'order_type' => 'new_purchase',
            'status' => 'pending',
            'payment_status' => 'paid',
            'payable_amount' => 9,
            'paid_amount' => 9,
            'meta' => [
                'subscription_activation_error' => [
                    'message' => 'sync failed',
                ],
            ],
        ]);

        PlatformOrder::query()->create([
            'merchant_id' => $merchantId,
            'plan_id' => null,
            'site_subscription_id' => null,
            'created_by_admin_id' => $platformAdminId ?: null,
            'order_no' => 'PO_DASH_BMPA_FAILED_0001',
            'order_type' => 'new_purchase',
            'status' => 'pending',
            'payment_status' => 'unpaid',
            'payable_amount' => 9,
            'paid_amount' => 0,
            'meta' => [
                'batch_mark_paid_and_activate_error' => [
                    'message' => 'bmpa failed',
                ],
            ],
        ]);

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

        $res->assertSee('PO_DASH_SYNC_FAILED_0001');
        $res->assertSee('同步失败', false);

        $syncFailedUrl = '/admin/platform-orders?' . Arr::query([
            'sync_status' => 'failed',
            'back' => '/admin',
        ]);
        $res->assertSee($syncFailedUrl, false);

        $res->assertSee('PO_DASH_BMPA_FAILED_0001');
        $res->assertSee('BMPA失败', false);

        $bmpaFailedUrl = '/admin/platform-orders?' . Arr::query([
            'bmpa_failed_only' => '1',
            'back' => '/admin',
        ]);
        $res->assertSee($bmpaFailedUrl, false);

        // 不应出现 &amp;back=，避免回跳断链
        $res->assertDontSee('&amp;back=', false);
    }
}
