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

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

        $merchantA = Merchant::query()->firstOrFail();
        $merchantB = Merchant::query()->create([
            'name' => '另一个演示站点',
            'slug' => 'demo-merchant-b',
            'status' => 'active',
        ]);

        $plan = Plan::query()->create([
            'code' => 'mismatch_guard_test_plan',
            'name' => '站点不一致护栏测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

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

        $order = PlatformOrder::query()->create([
            'merchant_id' => $merchantB->id,
            'plan_id' => $plan->id,
            'site_subscription_id' => $sub->id,
            'order_no' => 'PO_MERCHANT_MISMATCH_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),
        ]);

        $this->expectException(\InvalidArgumentException::class);

        $service = new SubscriptionActivationService();
        $service->activateOrder($order->id, 1);
    }
}
