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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'sub_index_row_renew_plan',
            'name' => '订阅列表行续费下单链接测试套餐',
            '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_ROW_RENEW_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(),
        ]);

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

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

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

        $html = (string) $res->getContent();

        // 不依赖 query 顺序：解析 href 后按键值断言
        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['site_subscription_id'] ?? '') === (string) $sub->id
                && (string) ($q['merchant_id'] ?? '') === (string) $merchant->id
                && (string) ($q['plan_id'] ?? '') === (string) $plan->id
                && (string) ($q['quantity'] ?? '') === '1'
                && str_contains((string) ($q['remark'] ?? ''), $sub->subscription_no)
                && (string) ($q['back'] ?? '') === $selfWithoutBack) {
                $found = true;
                // 防 back 嵌套
                $this->assertStringNotContainsString('back%3D', $u);
                break;
            }
        }

        $this->assertTrue($found, '未找到包含 subscription_id 与 back 的续费下单链接');
        $res->assertSee('续费下单', false);
    }
}
