<?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\Queue;
use Tests\TestCase;

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

        Queue::fake();

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

        $processable = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_BMPA_DISPATCH_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();

        Queue::assertPushed(BatchMarkPaidAndActivateJob::class, function (BatchMarkPaidAndActivateJob $job) use ($processable) {
            return in_array($processable->id, $job->orderIds, true)
                && $job->scope === 'filtered'
                && $job->limit === 50
                && str_starts_with($job->runId, 'BMPA');
        });

        // 不应在请求内就完成推进（因为我们已队列化）；因此订单仍应是 pending+unpaid
        $processable->refresh();
        $this->assertSame('pending', $processable->status);
        $this->assertSame('unpaid', $processable->payment_status);
    }
}
