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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'bmpa_last_result_summary_plan',
            'name' => 'BMPA last_result 汇总写入测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 30,
            'list_price' => 30,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        // A：可处理
        $a = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_BMPA_LR_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),
        ]);

        // B：制造失败（已有回执证据但金额不一致）
        $b = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_BMPA_LR_0002',
            '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(9),
            'meta' => [
                'payment_summary' => [
                    'count' => 1,
                    'total_amount' => 1.00,
                ],
            ],
        ]);

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

        $a->refresh();
        $b->refresh();

        $runIdA = (string) data_get($a->meta, 'batch_mark_paid_and_activate.run_id');
        $runIdB = (string) data_get($b->meta, 'batch_mark_paid_and_activate.run_id');

        $this->assertNotSame('', $runIdA);
        $this->assertSame($runIdA, $runIdB);

        $lrA = (array) (data_get($a->meta, 'batch_mark_paid_and_activate.last_result') ?? []);
        $lrB = (array) (data_get($b->meta, 'batch_mark_paid_and_activate.last_result') ?? []);

        $this->assertSame($runIdA, (string) ($lrA['run_id'] ?? ''));
        $this->assertSame($runIdA, (string) ($lrB['run_id'] ?? ''));

        $this->assertSame(1, (int) ($lrA['success'] ?? 0));
        $this->assertSame(1, (int) ($lrA['failed'] ?? 0));
        $this->assertSame(2, (int) ($lrA['matched'] ?? 0));
        $this->assertSame(2, (int) ($lrA['processed'] ?? 0));

        $this->assertNotEmpty($lrA['top_reasons'] ?? []);
    }
}
