<?php

namespace Tests\Feature;

use App\Models\Merchant;
use App\Models\Plan;
use App\Models\PlatformOrder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'po_show_find_sub_attach_order_plan',
            'name' => '订单详情 查找订阅链接携带 attach_order_id 测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 30,
            'list_price' => 30,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $order = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_SHOW_FIND_SUB_ATTACH_ORDER_0001',
            'order_type' => 'renewal',
            'status' => 'pending',
            'payment_status' => 'unpaid',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'payable_amount' => 30,
            'paid_amount' => 0,
            'placed_at' => now(),
            'meta' => [],
        ]);

        $res = $this->get('/admin/platform-orders/' . $order->id);
        $res->assertOk();

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

        // 仍应包含 merchant_id/plan_id/back
        $this->assertStringContainsString('/admin/site-subscriptions?', $html);
        $this->assertStringContainsString('merchant_id=' . $merchant->id, $html);
        $this->assertStringContainsString('plan_id=' . $plan->id, $html);
        $this->assertStringContainsString('back=' . urlencode('/admin/platform-orders/' . $order->id), $html);

        // 新增：应携带 attach_order_id/attach_back，支持订阅列表行内一键绑定并回跳
        $this->assertStringContainsString('attach_order_id=' . $order->id, $html);
        $this->assertStringContainsString('attach_back=' . urlencode('/admin/platform-orders/' . $order->id), $html);
    }
}
