<?php

namespace Tests\Unit;

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

class PlatformOrderRefundInconsistentToleranceConfigTest extends TestCase
{
    use RefreshDatabase;

    public function test_is_refund_inconsistent_respects_configured_tolerance(): void
    {
        config(['saasshop.amounts.tolerance' => 0.05]);

        $merchant = Merchant::query()->create([
            'name' => '容差单测站点',
            'slug' => 'unit-test-merchant-refund-tol',
            'status' => 'active',
        ]);

        $plan = Plan::query()->create([
            'code' => 'unit_test_plan_refund_tol_1',
            'name' => '容差单测套餐',
            'billing_cycle' => 'monthly',
            'price' => 10,
            'list_price' => 10,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        // 场景1：状态=refunded，但退款总额只差 0.02（在容差 0.05 内）=> 不应判定不一致
        $order1 = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_UNIT_REFUND_TOL_0001',
            'order_type' => 'subscription',
            'status' => 'activated',
            'payment_status' => 'refunded',
            'plan_name' => 'Unit Test Plan',
            'billing_cycle' => 'monthly',
            'period_months' => 1,
            'quantity' => 1,
            'payable_amount' => 10,
            'paid_amount' => 10,
            'placed_at' => now(),
            'meta' => [
                'refund_summary' => [
                    'total_amount' => 9.98,
                ],
            ],
        ]);

        $this->assertFalse($order1->isRefundInconsistent());

        // 场景2：状态!=refunded，但退款总额只比已付多 0.02（在容差 0.05 内）=> 不应判定不一致
        $order2 = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_UNIT_REFUND_TOL_0002',
            'order_type' => 'subscription',
            'status' => 'activated',
            'payment_status' => 'paid',
            'plan_name' => 'Unit Test Plan',
            'billing_cycle' => 'monthly',
            'period_months' => 1,
            'quantity' => 1,
            'payable_amount' => 10,
            'paid_amount' => 10,
            'placed_at' => now(),
            'meta' => [
                'refund_summary' => [
                    'total_amount' => 10.02,
                ],
            ],
        ]);

        $this->assertFalse($order2->isRefundInconsistent());
    }
}
