<?php

namespace Tests\Feature;

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

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

        $back = '/admin/site-subscriptions/1';

        $this->get('/admin/platform-orders/create?back=' . urlencode($back))
            ->assertOk()
            ->assertSee('返回上一页（保留上下文）')
            ->assertSee('href="' . $back . '"', false)
            ->assertSee('name="back"', false);
    }

    public function test_store_redirects_to_show_with_back_when_back_is_safe_relative_path(): void
    {
        $this->loginAsPlatformAdmin();

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'po_create_back_flow_plan',
            'name' => '创建订单 back 流程测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $back = '/admin/site-subscriptions/123?status=activated';

        $res = $this->post('/admin/platform-orders', [
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_type' => 'new_purchase',
            'quantity' => 1,
            'discount_amount' => 0,
            'payment_channel' => 'offline',
            'remark' => 'back flow',
            'back' => $back,
        ]);

        $res->assertRedirect();
        $location = $res->headers->get('Location');

        $this->assertNotNull($location);
        $this->assertStringContainsString('/admin/platform-orders/', $location);
        $this->assertStringContainsString('back=' . urlencode($back), $location);
    }
}
