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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'sub_index_create_order_plan',
            'name' => '订阅列表创建续费订单测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        SiteSubscription::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'status' => 'activated',
            'source' => 'manual',
            'subscription_no' => 'SUB_INDEX_CREATE_ORDER_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（避免嵌套），同时带 merchant_id/plan_id 筛选
        $currentUrl = '/admin/site-subscriptions?' . Arr::query([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'status' => 'activated',
            'back' => '/admin',
        ]);

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

        $selfWithoutBack = '/admin/site-subscriptions?' . Arr::query([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'status' => 'activated',
        ]);

        // 不依赖 query 顺序：解析 href 后按键值断言
        $html = $res->getContent();

        preg_match_all('/href="([^"]+)"/', $html, $matches);
        $hrefs = $matches[1] ?? [];

        $createUrls = array_values(array_filter($hrefs, fn ($u) => str_contains($u, '/admin/platform-orders/create?')));
        $this->assertNotEmpty($createUrls, '未找到创建续费订单链接');

        $found = false;
        foreach ($createUrls as $u) {
            $parts = parse_url($u);
            parse_str($parts['query'] ?? '', $q);

            if (($q['order_type'] ?? '') === 'renewal'
                && (string) ($q['merchant_id'] ?? '') === (string) $merchant->id
                && (string) ($q['plan_id'] ?? '') === (string) $plan->id
                && (string) ($q['back'] ?? '') === $selfWithoutBack) {
                $found = true;
                break;
            }
        }

        $this->assertTrue($found, '未找到包含当前筛选条件与 back 的续费下单链接');
        $res->assertSee('续费下单（先选订阅）', false);

        // 防 back 嵌套
        $res->assertDontSee('back%3D', false);
    }
}
