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

        // 设置较大的容差，验证 addRefundReceipt 的推进口径为：refund_total + tol >= paid
        config(['saasshop.amounts.tolerance' => 0.50]);

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'refund_receipt_tol_plan_01',
            '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_REFUND_RECEIPT_TOL_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(),
            'meta' => [],
        ]);

        // 退款 9.60；在 tol=0.50 下，应推进到 refunded
        $this->post('/admin/platform-orders/' . $order->id . '/add-refund-receipt', [
            'type' => 'refund',
            'channel' => 'wechat',
            'amount' => 9.60,
            'refunded_at' => now()->format('Y-m-d H:i:s'),
            'note' => '容差测试退款回执',
        ])->assertRedirect();

        $order->refresh();
        $this->assertSame('refunded', $order->payment_status);
        $this->assertNotNull($order->refunded_at);

        $refundSummaryTotal = (float) data_get($order->meta, 'refund_summary.total_amount');
        $this->assertSame(9.60, $refundSummaryTotal);
    }
}
