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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'po_show_activate_sub_btn_disable_renewal_no_sub_plan',
            'name' => '订单详情 同步订阅按钮禁用（续费无订阅）测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 50,
            'list_price' => 50,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $order = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_SHOW_ACT_SUB_DISABLE_RENEW_NO_SUB_0001',
            'order_type' => 'renewal',
            // 模拟脏数据：续费单已支付已生效，但未绑定订阅
            'status' => 'activated',
            'payment_status' => 'paid',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'payable_amount' => 50,
            'paid_amount' => 50,
            'placed_at' => now()->subMinutes(10),
            'paid_at' => now()->subMinutes(5),
            'activated_at' => now()->subMinutes(1),
            'meta' => [],
        ]);

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

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

        $this->assertStringContainsString('/admin/platform-orders/' . $order->id . '/activate-subscription', $html);

        // 同步订阅按钮应被禁用（disabled）
        $this->assertMatchesRegularExpression(
            '#/admin/platform-orders/' . $order->id . '/activate-subscription.*?<button[^>]*disabled#s',
            $html
        );

        // 治理提示 + 引导入口应出现
        $this->assertStringContainsString('同步订阅治理提示', $html);
        $this->assertStringContainsString('未绑定订阅', $html);
        $this->assertStringContainsString('去订阅管理查找订阅', $html);
        $this->assertStringContainsString('/admin/site-subscriptions?', $html);

        // back 应回到当前订单详情
        $this->assertStringContainsString('back=' . urlencode('/admin/platform-orders/' . $order->id), $html);
    }
}
