<?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 AdminPlatformOrderStoreRenewalShouldRejectMerchantMismatchTest 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_merchant_mismatch_with_subscription(): void
    {
        $this->loginAsPlatformAdmin();

        $merchantA = Merchant::query()->firstOrFail();
        $merchantB = Merchant::query()->create([
            'name' => '站点B',
            'slug' => 'merchant-b',
            'status' => 'active',
        ]);

        $plan = Plan::query()->create([
            'code' => 'po_store_renewal_merchant_mismatch_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_PO_STORE_MERCHANT_MISMATCH_0001',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->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' => $merchantB->id,
            'plan_id' => $plan->id,
            'site_subscription_id' => $sub->id,
            'order_type' => 'renewal',
            'quantity' => 1,
            'discount_amount' => 0,
            'payment_channel' => 'offline',
            'remark' => 'merchant mismatch',
        ]);

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