<?php

namespace Tests\Feature;

use App\Jobs\BatchMarkPaidAndActivateJob;
use App\Models\Merchant;
use App\Models\Plan;
use App\Models\PlatformOrder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;

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

        Queue::fake();
        Cache::flush();

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'batch_bmpa_dedupe_plan',
            'name' => '批量 BMPA 去重投递测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 30,
            'list_price' => 30,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_BMPA_DEDUPE_0001',
            'order_type' => 'new_purchase',
            'status' => 'pending',
            'payment_status' => 'unpaid',
            'plan_name' => $plan->name,
            'billing_cycle' => $plan->billing_cycle,
            'period_months' => 1,
            'quantity' => 1,
            'payable_amount' => 30,
            'paid_amount' => 0,
            'placed_at' => now()->subMinutes(10),
        ]);

        // 第一次：应投递
        $this->post('/admin/platform-orders/batch-mark-paid-and-activate', [
            'scope' => 'filtered',
            'status' => 'pending',
            'payment_status' => 'unpaid',
            'limit' => 50,
        ])->assertRedirect();

        // 第二次（同一集合，1 分钟内）：应被阻断，不再投递
        $res2 = $this->post('/admin/platform-orders/batch-mark-paid-and-activate', [
            'scope' => 'filtered',
            'status' => 'pending',
            'payment_status' => 'unpaid',
            'limit' => 50,
        ]);

        $res2->assertRedirect();
        $res2->assertSessionHas('warning');

        // 提示应带出 run_id（短展示）关键片段，避免运营不知道是哪一批。
        $res2->assertSessionHas('warning', fn ($v) => is_string($v) && str_contains($v, 'run_id='));

        Queue::assertPushed(BatchMarkPaidAndActivateJob::class, 1);
    }
}
