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

        config(['saasshop.amounts.tolerance' => 0.05]);

        $merchant = Merchant::query()->firstOrFail();
        $plan = Plan::query()->create([
            'code' => 'mark_paid_tol_cfg_plan',
            'name' => '标记支付容差配置测试（月付）',
            'billing_cycle' => 'monthly',
            'price' => 30,
            'list_price' => 30,
            'status' => 'active',
            'sort' => 10,
            'published_at' => now(),
        ]);

        // 订单应付 30.00，已有回执 30.02（差 0.02），在容差 0.05 内，不应阻断
        $order = PlatformOrder::query()->create([
            'merchant_id' => $merchant->id,
            'plan_id' => $plan->id,
            'order_no' => 'PO_MARK_PAID_TOL_CFG_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' => [
                'payment_summary' => [
                    'count' => 1,
                    'total_amount' => 30.02,
                ],
            ],
        ]);

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

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