<?php

namespace Tests\Feature;

use App\Jobs\BatchActivateSubscriptionsJob;
use App\Models\Merchant;
use App\Models\Plan;
use App\Models\PlatformOrder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'job_batch_activate_run_id_plan',
            'name' => 'Job 批量同步 run_id 测试套餐',
            '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_JOB_BATCH_RUN_ID_0001',
            'order_type' => 'new_purchase',
            'status' => 'activated',
            '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()->subMinutes(10),
            'paid_at' => now()->subMinutes(9),
            'activated_at' => now()->subMinutes(8),
            'meta' => [],
        ]);

        // 同步执行 job 的 handle（不依赖 queue worker），用于锁定写入口径
        $job = new BatchActivateSubscriptionsJob([
            $order->id,
        ], 1, 'filtered', 'syncable_only=1', 50, 1, 1);

        $job->handle(app(\App\Support\SubscriptionActivationService::class));

        $order->refresh();

        $this->assertNotEmpty((string) data_get($order->meta, 'batch_activation.run_id'));
        $this->assertSame((string) data_get($order->meta, 'batch_activation.run_id'), (string) data_get($order->meta, 'audit.0.run_id'));

        $runId = (string) data_get($order->meta, 'batch_activation.run_id');
        $this->assertStringStartsWith('BAS', $runId);
    }
}
