<?php

namespace Tests\Feature;

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

/**
 * 收费闭环异常分支（可验收 SOP）：
 * 新购订单若已存在支付回执但总额与应付不一致，则 BMPA 应阻断；
 * 运营补齐差额回执后，BMPA 可继续推进并同步订阅。
 */
class AdminBillingClosedLoopNewPurchaseSopReceiptMismatchShouldBlockBmpaThenFixAndPassTest 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_sop_new_purchase_receipt_mismatch_should_block_bmpa_then_fix_and_pass(): void
    {
        $this->loginAsPlatformAdmin();

        $merchant = Merchant::query()->firstOrFail();

        $plan = Plan::query()->create([
            'code' => 'sop_new_purchase_receipt_mismatch_monthly',
            'name' => 'SOP新购（回执不一致治理）月付',
            'billing_cycle' => 'monthly',
            'price' => 30,
            'list_price' => 30,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        // 1) 创建平台订单（新购）
        $this->post('/admin/platform-orders', [
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_type' => 'new_purchase',
            'quantity' => 1,
            'discount_amount' => 0,
            'payment_channel' => 'bank_transfer',
            'remark' => 'SOP 新购（回执不一致）',
        ])->assertRedirect();

        /** @var PlatformOrder $order */
        $order = PlatformOrder::query()->latest('id')->firstOrFail();
        $this->assertSame('unpaid', (string) $order->payment_status);
        $this->assertSame('pending', (string) $order->status);
        $this->assertSame(30.0, (float) $order->payable_amount);

        // 2) 追加一笔金额不一致的支付回执（例如少 1 元）
        $this->post('/admin/platform-orders/' . $order->id . '/add-payment-receipt', [
            'type' => 'bank_transfer',
            'channel' => 'icbc',
            'amount' => 29,
            'paid_at' => now()->format('Y-m-d H:i:s'),
            'note' => '金额不一致（测试）',
        ])->assertRedirect();

        $order->refresh();
        $this->assertSame(29.0, (float) data_get($order->meta, 'payment_summary.total_amount'));

        // 3) BMPA 应阻断（避免带病推进）
        $res = $this->from('/admin/platform-orders/' . $order->id)
            ->post('/admin/platform-orders/' . $order->id . '/mark-paid-and-activate');

        $res->assertRedirect('/admin/platform-orders/' . $order->id);
        $res->assertSessionHas('warning');

        $order->refresh();
        $this->assertSame('unpaid', (string) $order->payment_status);
        $this->assertSame('pending', (string) $order->status);

        // 4) 运营补齐差额回执（+1）后，BMPA 应可继续推进
        $this->post('/admin/platform-orders/' . $order->id . '/add-payment-receipt', [
            'type' => 'bank_transfer',
            'channel' => 'icbc',
            'amount' => 1,
            'paid_at' => now()->format('Y-m-d H:i:s'),
            'note' => '补齐差额（测试）',
        ])->assertRedirect();

        $order->refresh();
        $this->assertSame(30.0, (float) data_get($order->meta, 'payment_summary.total_amount'));

        $this->post('/admin/platform-orders/' . $order->id . '/mark-paid-and-activate')
            ->assertRedirect();

        $order->refresh();
        $this->assertSame('paid', (string) $order->payment_status);
        $this->assertSame('activated', (string) $order->status);
        $this->assertNotNull($order->site_subscription_id);
    }
}
