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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'po_defaults_autofill_from_sub_plan',
            'name' => '创建订单默认值：从订阅补齐 merchant/plan 测试套餐',
            '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_AUTOFILL_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(),
        ]);

        // 仅传 site_subscription_id，不传 merchant_id / plan_id
        $url = '/admin/platform-orders/create?site_subscription_id=' . $sub->id . '&order_type=renewal';

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

        // 应自动预选订阅所属站点/套餐
        $res->assertSee('<option value="' . $merchant->id . '" selected>', false);
        $res->assertSee('<option value="' . $plan->id . '" selected>', false);

        // 订阅 hidden input 仍应存在
        $res->assertSee('name="site_subscription_id" value="' . $sub->id . '"', false);
    }
}
