<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

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

        $unsafeBack = '/admin/platform-orders?keyword="x"&a=<b>';

        $res = $this->get('/admin/plans/create?back=' . urlencode($unsafeBack));
        $res->assertOk();

        // form hidden input 不应出现 unsafe back
        $res->assertDontSee('name="back"', false);
        $res->assertDontSee($unsafeBack, false);
    }

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

        $nestedBack = '/admin/platform-orders?status=pending&back=/admin/plans';

        $res = $this->get('/admin/plans/create?back=' . urlencode($nestedBack));
        $res->assertOk();

        $res->assertDontSee('name="back"', false);
        $res->assertDontSee($nestedBack, false);
    }

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

        $unsafeBack = '/admin/platform-orders?keyword="x"&a=<b>';

        $res = $this->post('/admin/plans', [
            'code' => 'plan_back_unsafe_01',
            'name' => 'plan back unsafe',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'description' => '',
            'published_at' => now()->toDateTimeString(),
            'back' => $unsafeBack,
        ]);

        // unsafe back 应被忽略，回到列表页
        $res->assertRedirect('/admin/plans');
    }
}
