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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'po_syncable_exclude_renewal_missing_sub_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,
            'order_no' => 'PO_SYNCABLE_BAD_RENEW_NO_SUB_0001',
            'order_type' => 'renewal',
            '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()->subMinutes(10),
            'paid_at' => now()->subMinutes(9),
            'activated_at' => now()->subMinutes(8),
            'meta' => [],
        ]);

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

        // 当前测试场景下，只有这一个“看似可同步”的订单，但它应被排除，因此可同步数应为 0
        $res->assertSee('可同步订单');
        $res->assertSee('>0<', false);
    }
}
