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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'activate_subscription_renewal_missing_sub_plan',
            'name' => '同步订阅阻断（续费无订阅）测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 88,
            'list_price' => 88,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $order = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_ACT_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' => 88,
            'paid_amount' => 88,
            'placed_at' => now()->subMinutes(10),
            'paid_at' => now()->subMinutes(5),
            'activated_at' => now()->subMinutes(1),
            'meta' => [],
        ]);

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

        $order->refresh();
        $this->assertNull($order->site_subscription_id);
    }
}
