<?php

namespace Tests\Feature;

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

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

        $merchant = Merchant::query()->firstOrFail();

        $plan = Plan::query()->create([
            'code' => 'sub_index_attach_order_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' => 'active',
            'source' => 'manual',
            'subscription_no' => 'SS_ATTACH_ORDER_BTN_0001',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'amount' => 10,
            'starts_at' => now()->subDays(1),
            'ends_at' => now()->addDays(10),
            'snapshot' => [],
            'meta' => [],
        ]);

        $orderId = 12345;

        $res = $this->get('/admin/site-subscriptions?attach_order_id=' . $orderId . '&attach_back=%2Fadmin%2Fplatform-orders%2F1');
        $res->assertOk();

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

        // 去重降噪：处于 attach_order_id 模式时，不应出现任何“续费下单”入口（包含工具入口与行内按钮）
        $this->assertStringNotContainsString('续费下单（先选订阅）', $html);
        $this->assertStringNotContainsString('>续费下单<', $html);

        // attach_order 模式下不应出现“更新订阅状态”入口（避免运营走偏）
        $this->assertStringNotContainsString('/admin/site-subscriptions/' . $sub->id . '/set-status', $html);

        // 顶部应有“返回订单详情”入口，避免运营迷路
        $this->assertStringContainsString('返回订单详情', $html);
        $this->assertStringContainsString('/admin/platform-orders/1', $html);

        $this->assertStringContainsString('绑定到订单 #' . $orderId, $html);
        $this->assertStringContainsString('/admin/platform-orders/' . $orderId . '/attach-subscription', $html);
        $this->assertStringContainsString('name="site_subscription_id" value="' . $sub->id . '"', $html);
    }
}
