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

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

        $plan = Plan::query()->create([
            'code' => 'sub_show_rms_link_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_SHOW_RMS_LINK_0001',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'amount' => 10,
            'starts_at' => now(),
            'ends_at' => now()->addMonth(),
        ]);

        $res = $this->get('/admin/site-subscriptions/' . $sub->id);
        $res->assertOk();

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

        $this->assertStringContainsString('查看续费缺订阅订单（同站点/同套餐）', $html);
        $this->assertStringContainsString('/admin/platform-orders?', $html);
        $this->assertStringContainsString('merchant_id=' . $merchant->id, $html);
        $this->assertStringContainsString('plan_id=' . $plan->id, $html);
        $this->assertStringContainsString('renewal_missing_subscription=1', $html);

        // back 应回到订阅详情自身
        $this->assertStringContainsString('back=' . urlencode('/admin/site-subscriptions/' . $sub->id), $html);
    }
}
