<?php

namespace Tests\Feature;

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

class AdminPlatformOrderActivateSubscriptionShouldExtendEndsAtForRenewalOrderTest 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_extend_existing_subscription_for_renewal_order(): void
    {
        $this->loginAsPlatformAdmin();

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

        $plan = Plan::query()->create([
            'code' => 'renew_extend_test_plan',
            'name' => '续费延长到期测试（月付）',
            'billing_cycle' => 'monthly',
            'price' => 66,
            'list_price' => 66,
            '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_RENEW_EXT_0001',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'amount' => 66,
            'starts_at' => now()->subMonth(),
            'ends_at' => now()->addDays(20),
            'activated_at' => now()->subMonth(),
        ]);

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

        $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' => 1,
            'list_amount' => 66,
            'discount_amount' => 0,
            'payable_amount' => 66,
            'paid_amount' => 66,
            'placed_at' => now()->subMinutes(10),
            'paid_at' => now()->subMinutes(5),
            'activated_at' => now()->subMinutes(1),
            // 避免命中治理安全阀
            'meta' => [
                'payment_summary' => [
                    'count' => 1,
                    'total_amount' => 66.00,
                ],
            ],
        ]);

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

        $sub->refresh();

        $this->assertTrue($sub->ends_at->greaterThan($oldEndsAt), '续费后 ends_at 应延长');
    }
}
