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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'mark_paid_renewal_requires_sub_guard_plan',
            'name' => '标记支付续费必须绑订阅安全阀测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 30,
            'list_price' => 30,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        // 人为构造“脏数据”：renewal 但 site_subscription_id 为空
        $order = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_MARK_PAID_RENEWAL_NO_SUB_0001',
            'order_type' => 'renewal',
            'status' => 'pending',
            'payment_status' => 'unpaid',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'payable_amount' => 30,
            'paid_amount' => 0,
            'placed_at' => now(),
            'meta' => [],
        ]);

        $res = $this->post('/admin/platform-orders/' . $order->id . '/mark-paid-and-activate');
        $res->assertRedirect();
        $res->assertSessionHas('warning');

        $order->refresh();
        $this->assertSame('unpaid', $order->payment_status);
        $this->assertSame('pending', $order->status);
        $this->assertNull($order->site_subscription_id);
    }
}
