<?php

namespace Tests\Feature;

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

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

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

        $planA = Plan::query()->create([
            'code' => 'po_store_renewal_plan_mismatch_plan_a',
            'name' => '续费下单套餐不一致拒绝测试套餐A',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $planB = Plan::query()->create([
            'code' => 'po_store_renewal_plan_mismatch_plan_b',
            'name' => '续费下单套餐不一致拒绝测试套餐B',
            'billing_cycle' => 'monthly',
            'price' => 20,
            'list_price' => 20,
            'status' => 'active',
            'sort' => 9,
            'published_at' => now(),
        ]);

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

        $res = $this->from('/admin/platform-orders/create')->post('/admin/platform-orders', [
            'merchant_id' => $merchant->id,
            'plan_id' => $planB->id,
            'site_subscription_id' => $sub->id,
            'order_type' => 'renewal',
            'quantity' => 1,
            'discount_amount' => 0,
            'payment_channel' => 'offline',
            'remark' => 'plan mismatch',
        ]);

        $res->assertStatus(302);
        $res->assertSessionHasErrors('plan_id');
    }
}
