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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'create_defaults_preselect_plan',
            'name' => '创建订单默认值预选测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 100,
            'list_price' => 100,
            '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_CREATE_DEFAULTS_0001',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'amount' => 100,
            'starts_at' => now()->subDay(),
            'ends_at' => now()->addMonth(),
            'activated_at' => now()->subDay(),
        ]);

        $url = '/admin/platform-orders/create?merchant_id=' . $merchant->id
            . '&plan_id=' . $plan->id
            . '&site_subscription_id=' . $sub->id
            . '&order_type=renewal'
            . '&quantity=2'
            . '&discount_amount=3.5'
            . '&payment_channel=offline'
            . '&remark=' . urlencode('来自订阅：' . $sub->subscription_no);

        $res = $this->get($url);
        $res->assertOk();

        // 预选 merchant/plan/order_type
        $res->assertSee('<option value="' . $merchant->id . '" selected>', false);
        $res->assertSee('<option value="' . $plan->id . '" selected>', false);
        // 兼容不同 Laravel 版本对 @selected 的渲染形式（selected 或 selected="selected"）
        $res->assertSee('value="renewal" selected', false);

        // 预填其它字段
        $res->assertSee('name="site_subscription_id" value="' . $sub->id . '"', false);
        $res->assertSee('name="quantity" value="2"', false);
        $res->assertSee('name="discount_amount" value="3.5"', false);
        $res->assertSee('name="payment_channel" value="offline"', false);
        $res->assertSee('来自订阅：' . $sub->subscription_no, false);
    }
}
