<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

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

        // 需要先造数据，确保 expiring_7d 聚合表格不为空。
        $m1 = \App\Models\Merchant::query()->firstOrFail();
        $plan = \App\Models\Plan::query()->create([
            'code' => 'sub_expiry_top10_cta_plan',
            'name' => '到期治理 CTA 测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 1,
            'list_price' => 1,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        \App\Models\SiteSubscription::query()->create([
            'merchant_id' => $m1->id,
            'plan_id' => $plan->id,
            'status' => 'activated',
            'source' => 'manual',
            'subscription_no' => 'SUB_EXP_TOP10_CTA_0001',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'amount' => 1,
            'starts_at' => now()->subDays(10),
            'ends_at' => now()->addDays(3),
            'activated_at' => now()->subDays(10),
        ]);

        $res = $this->get('/admin/site-subscriptions?expiry=expiring_7d');
        $res->assertOk();

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

        $this->assertStringContainsString('站点维度提醒清单', $html);
        $this->assertStringContainsString('去创建续费订单', $html);

        // CTA 链接应指向下单页，并带 require_subscription=1，且 back 必须回到仪表盘（selfWithoutBack=/admin）。
        $this->assertStringContainsString('/admin/platform-orders/create?', $html);
        $this->assertStringContainsString('order_type=renewal', $html);
        $this->assertStringContainsString('require_subscription=1', $html);
        $this->assertStringContainsString('back=%2Fadmin', $html);
    }
}
