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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'sub_expiry_top10_cta_plan_with_plan_id',
            'name' => '到期治理 CTA（带 plan_id）测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 1,
            'list_price' => 1,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        SiteSubscription::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'status' => 'activated',
            'source' => 'manual',
            'subscription_no' => 'SUB_EXP_TOP10_CTA_PLAN_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('data-role="expiring-7d-merchant-plan-top10"', $html);

        // CTA 链接应包含 merchant_id + plan_id，并保持 require_subscription=1。
        $this->assertStringContainsString('/admin/platform-orders/create?', $html);
        $this->assertStringContainsString('order_type=renewal', $html);
        $this->assertStringContainsString('require_subscription=1', $html);
        $this->assertStringContainsString('merchant_id=' . $merchant->id, $html);
        $this->assertStringContainsString('plan_id=' . $plan->id, $html);

        // back 必须回到仪表盘（selfWithoutBack=/admin）。
        $this->assertStringContainsString('back=%2Fadmin', $html);
    }
}
