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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'po_show_forms_disable_submit_01',
            'name' => '订单详情表单禁用提交测试',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $order = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_SHOW_DISABLE_SUBMIT_0001',
            'order_type' => 'new_purchase',
            'status' => 'pending',
            'payment_status' => 'paid',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'payable_amount' => 10,
            'paid_amount' => 10,
            'placed_at' => now(),
            'paid_at' => now(),
            'meta' => [
                // 让页面出现“同步失败/ BMPA失败”的清理按钮（否则按钮不渲染）
                'subscription_activation_error' => [
                    'message' => 'sync failed',
                    'at' => now()->toDateTimeString(),
                ],
                'batch_mark_paid_and_activate_error' => [
                    'message' => 'bmpa failed',
                    'at' => now()->toDateTimeString(),
                ],
            ],
        ]);

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

        $this->assertIsString($html);

        // 标记生效
        $this->assertStringContainsString('/admin/platform-orders/' . $order->id . '/mark-activated', $html);
        $this->assertStringContainsString('data-action="disable-on-submit"', $html);

        // 清除失败标记（同步/BMPA）
        $this->assertStringContainsString('/admin/platform-orders/' . $order->id . '/clear-sync-error', $html);
        $this->assertStringContainsString('/admin/platform-orders/' . $order->id . '/clear-bmpa-error', $html);
        $this->assertStringContainsString('data-action="disable-on-submit"', $html);
    }
}
