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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'batch_mark_paid_and_activate_plan',
            'name' => '批量标记支付并生效测试套餐',
            '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_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_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,
                ],
            ],
        ]);

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

        $res->assertRedirect();

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

        // A：已推进并同步订阅
        $this->assertSame('paid', $a->payment_status);
        $this->assertSame('activated', $a->status);
        $this->assertNotNull($a->site_subscription_id);
        $this->assertNotNull(data_get($a->meta, 'subscription_activation.subscription_id'));
        $this->assertSame('batch_mark_paid_and_activate', data_get($a->meta, 'audit.0.action'));

        // B：不应被推进
        $this->assertSame('unpaid', $b->payment_status);
        $this->assertSame('pending', $b->status);
        $this->assertNull($b->site_subscription_id);
        $this->assertNotEmpty(data_get($b->meta, 'batch_mark_paid_and_activate_error.message'));
    }

    public function test_batch_mark_paid_and_activate_requires_pending_and_unpaid_filters_in_filtered_scope(): void
    {
        $this->loginAsPlatformAdmin();

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

        $res->assertRedirect();
        $res->assertSessionHas('warning');
    }
}
