<?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 AdminSubscriptionActivationRenewalExtendsEndsAtTest extends TestCase
{
    use RefreshDatabase;

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

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

        $plan = Plan::query()->create([
            'code' => 'renew_extend_test',
            'name' => '续期延长到期测试（月付）',
            'billing_cycle' => 'monthly',
            'price' => 99,
            'list_price' => 99,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        // 构造一个仍有效的订阅：ends_at 在未来
        $sub = SiteSubscription::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'status' => 'activated',
            'source' => 'manual',
            'subscription_no' => 'SUB_RENEW_EXT_0001',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'amount' => 99,
            'starts_at' => now()->subDays(10),
            'ends_at' => now()->addDays(20),
            'activated_at' => now()->subDays(10),
        ]);

        $oldEndsAt = $sub->ends_at->copy();

        // 构造一笔续费订单，绑定该订阅，购买 2 个月（period_months=1, quantity=2 => months=2）
        $order = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'site_subscription_id' => $sub->id,
            'order_no' => 'PO_RENEW_EXT_0001',
            'order_type' => 'renewal',
            'status' => 'activated',
            'payment_status' => 'paid',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 2,
            'list_amount' => 198,
            'discount_amount' => 0,
            'payable_amount' => 198,
            'paid_amount' => 198,
            'placed_at' => now()->subMinutes(10),
            'paid_at' => now()->subMinutes(5),
            'activated_at' => now()->subMinutes(1),
        ]);

        $service = app(SubscriptionActivationService::class);
        $service->activateOrder($order->id, 1);

        $sub->refresh();

        $this->assertTrue($sub->ends_at->greaterThan($oldEndsAt));
        $this->assertSame(
            $oldEndsAt->copy()->addMonthsNoOverflow(2)->format('Y-m-d H:i:s'),
            $sub->ends_at->format('Y-m-d H:i:s')
        );
    }

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

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

        $plan = Plan::query()->create([
            'code' => 'renew_extend_test2',
            'name' => '续期延长到期测试（已过期）',
            'billing_cycle' => 'monthly',
            'price' => 99,
            'list_price' => 99,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        // 构造一个已过期订阅：ends_at 在过去
        $sub = SiteSubscription::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'status' => 'cancelled',
            'source' => 'manual',
            'subscription_no' => 'SUB_RENEW_EXT_0002',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'amount' => 99,
            'starts_at' => now()->subMonths(2),
            'ends_at' => now()->subDays(1),
            'activated_at' => now()->subMonths(2),
            'cancelled_at' => now()->subDays(1),
        ]);

        // 续费 1 个月
        $order = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'site_subscription_id' => $sub->id,
            'order_no' => 'PO_RENEW_EXT_0002',
            'order_type' => 'renewal',
            'status' => 'activated',
            'payment_status' => 'paid',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'list_amount' => 99,
            'discount_amount' => 0,
            'payable_amount' => 99,
            'paid_amount' => 99,
            'placed_at' => now()->subMinutes(10),
            'paid_at' => now()->subMinutes(5),
            'activated_at' => now()->subMinutes(1),
        ]);

        $service = app(SubscriptionActivationService::class);
        $service->activateOrder($order->id, 1);

        $sub->refresh();

        $this->assertSame('activated', $sub->status);
        $this->assertNotNull($sub->ends_at);
        $this->assertTrue($sub->ends_at->greaterThan(now()));
    }
}
