<?php

namespace Tests\Feature;

use App\Models\Merchant;
use App\Models\Plan;
use App\Models\PlatformOrder;
use App\Models\SiteSubscription;
use App\Support\SubscriptionActivationService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class AdminSubscriptionActivationIdempotentTest extends TestCase
{
    use RefreshDatabase;

    public function test_activate_order_is_idempotent_when_meta_has_subscription_activation(): void
    {
        $this->seed();

        $merchant = Merchant::query()->firstOrFail();

        $plan = Plan::query()->create([
            'code' => 'activation_idempotent_test',
            'name' => '订阅激活幂等测试',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $sub = SiteSubscription::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'status' => 'activated',
            'source' => 'manual',
            'subscription_no' => 'SUB_IDEMP_0001',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'amount' => 10,
            'starts_at' => now()->subDays(2),
            'ends_at' => now()->addDays(20),
            'activated_at' => now()->subDays(2),
        ]);

        $service = app(SubscriptionActivationService::class);

        $order = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'site_subscription_id' => $sub->id,
            'order_no' => 'PO_IDEMP_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(5),
            'activated_at' => now()->subMinutes(1),
        ]);

        // 第一次激活：会写入 subscription_activation meta，并可能续期
        $service->activateOrder($order->id, 1);
        $order->refresh();
        $sub->refresh();

        $firstEndsAt = $sub->ends_at->copy();
        $this->assertNotEmpty(data_get($order->meta, 'subscription_activation.subscription_id'));

        // 第二次激活：应直接返回，不再延长 ends_at
        $service->activateOrder($order->id, 1);
        $sub->refresh();

        $this->assertSame($firstEndsAt->format('Y-m-d H:i:s'), $sub->ends_at->format('Y-m-d H:i:s'));
    }
}
