<?php

namespace Tests\Feature;

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

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

        $plan = Plan::query()->create([
            'code' => 'plan_edit_link_back_test',
            'name' => '套餐编辑链接 back 测试',
            'billing_cycle' => 'monthly',
            'price' => 99,
            'list_price' => 99,
            'status' => 'active',
            'sort' => 1,
            'published_at' => now(),
        ]);

        // 模拟：套餐列表页本身带 back（例如从别的模块跳转过来），避免 edit 链接把 back 再嵌套进去
        $currentUrl = '/admin/plans?' . Arr::query([
            'status' => 'active',
            'billing_cycle' => 'monthly',
            'back' => '/admin',
        ]);

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

        $selfWithoutBack = '/admin/plans?' . Arr::query([
            'status' => 'active',
            'billing_cycle' => 'monthly',
        ]);

        $expectedEditUrl = '/admin/plans/' . $plan->id . '/edit?' . Arr::query([
            'back' => $selfWithoutBack,
        ]);

        $res->assertSee($expectedEditUrl, false);

        // 防 back 嵌套：不应出现 back=...back=... 的编码片段
        $res->assertDontSee('back%3D', false);
    }
}
