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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'batch_activate_gov_safety_valve_test',
            'name' => '批量同步治理安全阀测试套餐',
            '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_BATCH_GOV_BLOCK_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(),
            'paid_at' => now(),
            'activated_at' => now(),
            // 对账不一致：receipt_total 9.98 vs paid_amount 10
            'meta' => [
                'payment_summary' => [
                    'count' => 1,
                    'total_amount' => 9.98,
                ],
            ],
        ]);

        $res = $this->post('/admin/platform-orders/batch-activate-subscriptions', [
            'scope' => 'filtered',
            'syncable_only' => '1',
            'reconcile_mismatch' => '1',
            'limit' => 50,
        ]);

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

        $order->refresh();
        $this->assertEmpty(data_get($order->meta, 'subscription_activation'));
    }
}
