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

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

        $plan = Plan::query()->create([
            'code' => 'sop_new_purchase_audit_receipts_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();

        // 2) 追加支付回执
        $this->post('/admin/platform-orders/' . $order->id . '/add-payment-receipt', [
            'type' => 'bank_transfer',
            'channel' => 'icbc',
            'amount' => 30,
            'paid_at' => now()->format('Y-m-d H:i:s'),
            'note' => '线下转账，财务已确认',
        ])->assertRedirect();

        $order->refresh();
        $audit = (array) (data_get($order->meta, 'audit', []) ?? []);
        $this->assertNotEmpty($audit);
        $last = end($audit);
        $this->assertSame('add_payment_receipt', (string) data_get($last, 'action'));
        $this->assertSame(30.0, (float) data_get($last, 'snapshot.amount'));

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

        $order->refresh();
        $this->assertSame('paid', (string) $order->payment_status);

        // 4) 追加退款回执（部分退款）
        $this->post('/admin/platform-orders/' . $order->id . '/add-refund-receipt', [
            'type' => 'refund',
            'channel' => 'icbc',
            'amount' => 10,
            'refunded_at' => now()->format('Y-m-d H:i:s'),
            'note' => '部分退款（测试）',
        ])->assertRedirect();

        $order->refresh();
        $audit = (array) (data_get($order->meta, 'audit', []) ?? []);
        $this->assertNotEmpty($audit);
        $last = end($audit);
        $this->assertSame('add_refund_receipt', (string) data_get($last, 'action'));
        $this->assertSame(10.0, (float) data_get($last, 'snapshot.amount'));
    }
}
