<?php

namespace App\Support;

use App\Models\AdminUser;
use App\Models\TransferOrder;
use App\Services\Wallet\LotteryTransferService;

/** 后台转账单可执行的对账/补单动作（列表与对账明细共用）。 */
final class AdminTransferOrderCapabilities
{
    public static function canWriteWallet(?AdminUser $admin): bool
    {
        if ($admin === null) {
            return false;
        }

        return $admin->hasPermissionCode('service.wallet.adjust')
            || $admin->hasPermissionCode('service.reconcile.manage')
            || $admin->hasPermissionCode('service.wallet.manage');
    }

    /**
     * @return array{
     *   can_reverse: bool,
     *   can_complete_credit: bool,
     *   can_manually_process: bool
     * }
     */
    public static function forOrder(TransferOrder $order, ?AdminUser $admin, LotteryTransferService $transferService): array
    {
        $canWrite = self::canWriteWallet($admin);

        return [
            'can_reverse' => $canWrite && $transferService->isEligibleForReverse($order),
            'can_complete_credit' => $canWrite
                && $order->direction === 'in'
                && $order->status === 'pending_reconcile'
                && $order->fail_reason === 'lottery_credit_failed'
                && trim((string) $order->external_ref_no) !== '',
            'can_manually_process' => $canWrite
                && $transferService->isEligibleForManualProcess($order),
        ];
    }
}
