<?php

namespace Tests\Feature;

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

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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'sub_index_sub_no_back_plan',
            'name' => '订阅列表订阅号 back 口径测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            '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_INDEX_BACK_0001',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'amount' => 10,
            'starts_at' => now()->subDay(),
            'ends_at' => now()->addMonth(),
            'activated_at' => now()->subDay(),
        ]);

        // 列表页带 back（模拟从其它页面跳回），index 内 back 口径用 selfWithoutBack（去掉 back）
        $res = $this->get('/admin/site-subscriptions?status=activated&back=' . urlencode('/admin/plans'));
        $res->assertOk();

        $expectedBack = '/admin/site-subscriptions?' . Arr::query([
            'status' => 'activated',
        ]);

        $expectedUrl = '/admin/site-subscriptions/' . $sub->id . '?' . Arr::query([
            'back' => $expectedBack,
        ]);

        $res->assertSee($expectedUrl, false);
        $res->assertDontSee('back%3D', false);
    }
}
