<?php

namespace Tests\Feature;

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

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

        $merchant = Merchant::query()->create([
            'name' => '校验失败回填站点',
            'slug' => 'validation-back-merchant',
            'status' => 'active',
        ]);

        $plan = Plan::query()->create([
            'code' => 'po_require_sub_persist_after_validation_error_plan',
            'name' => 'require_subscription 校验失败回填测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        // 关键点：from() 不带 require_subscription query，模拟“来源页没显式带 query”或被清洗掉。
        // 但表单提交时如果带了 require_subscription hidden input，校验失败 redirect back 后 create 页仍应保持治理口径。
        $res = $this->from('/admin/platform-orders/create')->post('/admin/platform-orders', [
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_type' => 'renewal',
            'require_subscription' => '1',
            'quantity' => 1,
            'discount_amount' => 0,
            'payment_channel' => 'offline',
            'remark' => 'test',
            // site_subscription_id 故意不传 => 触发校验失败
        ]);

        $res->assertStatus(302);
        $res->assertSessionHasErrors('site_subscription_id');

        $page = $this->get('/admin/platform-orders/create');
        $page->assertOk();

        // 治理口径仍应生效：仅允许 new_purchase，且应给出“去订阅管理选择订阅”入口
        $page->assertSee('value="new_purchase"', false);
        $page->assertDontSee('value="upgrade"', false);
        $page->assertDontSee('value="downgrade"', false);
        $page->assertSee('去订阅管理选择订阅', false);

        // 透传 hidden input，保证后续继续提交仍保持治理口径
        $page->assertSee('name="require_subscription" value="1"', false);
    }
}
