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

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'po_add_refund_receipt_unpaid_should_not_change_status',
            'name' => '追加退款回执不改变未支付状态测试套餐',
            'billing_cycle' => 'monthly',
            'price' => 30,
            'list_price' => 30,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        $order = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_ADD_REFUND_RECEIPT_UNPAID_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(),
            'meta' => [],
        ]);

        $this->post('/admin/platform-orders/' . $order->id . '/add-refund-receipt', [
            'type' => 'refund',
            'channel' => 'offline',
            'amount' => 1,
            'refunded_at' => now()->format('Y-m-d H:i:s'),
            'note' => '未支付订单的退款留痕',
        ])
            ->assertRedirect('/admin/platform-orders/' . $order->id . '#add-refund-receipt')
            ->assertSessionHas('success');

        $order->refresh();

        // 口径：未支付订单追加退款回执仅留痕，不自动推进支付状态（避免出现未付却部分退款/已退款的脏状态）。
        $this->assertSame('unpaid', (string) $order->payment_status);
        $this->assertNull($order->refunded_at);

        $this->assertSame(1, (int) data_get($order->meta, 'refund_summary.count'));
        $this->assertSame(1.0, (float) data_get($order->meta, 'refund_summary.total_amount'));
    }
}
