<?php

namespace Tests\Feature;

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

class AdminDashboardBillingWorkbenchSyncableCountShouldRenderTest 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_billing_workbench_syncable_count_should_render(): void
    {
        Cache::flush();

        $this->loginAsPlatformAdmin();

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

        // seed 已包含 1 条已支付+已生效且未写入 subscription_activation 的平台订单（可同步口径下应命中）
        // 这里再额外构造 1 条，最终期望显示为 2。
        PlatformOrder::query()->create([
            'merchant_id' => $merchantId,
            'plan_id' => null,
            'site_subscription_id' => 1,
            'created_by_admin_id' => $platformAdminId ?: null,
            'order_no' => 'PO_DASHBOARD_SYNCABLE_001',
            'order_type' => 'new_purchase',
            'status' => 'activated',
            'payment_status' => 'paid',
            'payable_amount' => 9,
            'paid_amount' => 9,
            'meta' => [],
        ]);

        // 同步失败单：不应计入“可同步”统计
        PlatformOrder::query()->create([
            'merchant_id' => $merchantId,
            'plan_id' => null,
            'site_subscription_id' => 1,
            'created_by_admin_id' => $platformAdminId ?: null,
            'order_no' => 'PO_DASHBOARD_SYNCABLE_BUT_FAILED_002',
            'order_type' => 'new_purchase',
            'status' => 'activated',
            'payment_status' => 'paid',
            'payable_amount' => 9,
            'paid_amount' => 9,
            'meta' => [
                'subscription_activation_error' => [
                    'message' => 'sync failed',
                ],
            ],
        ]);

        Cache::flush();

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

        $res->assertSee('可同步（2）');
    }
}
