<?php

namespace App\Support;

use App\Models\AdminUser;
use App\Services\LotterySettings;
use Illuminate\Validation\ValidationException;

final class AdminSettingPolicy
{
    private const WALLET_LIMIT_KEYS = [
        'wallet.transfer_in_min_minor',
        'wallet.transfer_in_max_minor',
        'wallet.transfer_out_min_minor',
        'wallet.transfer_out_max_minor',
    ];

    public static function canUpdate(AdminUser $admin, string $key): bool
    {
        if (LotterySettings::isEnvLocked($key)) {
            return false;
        }

        if (str_starts_with($key, 'settlement.')) {
            return $admin->hasAdminPermission('prd.payout.manage');
        }

        if (str_starts_with($key, 'draw.')) {
            return $admin->hasAdminPermission('prd.draw_result.manage');
        }

        if (str_starts_with($key, 'frontend.')) {
            return $admin->hasAdminPermission('prd.odds.manage')
                || $admin->hasAdminPermission('prd.rebate.manage');
        }

        if (str_starts_with($key, 'wallet.')) {
            return $admin->hasAdminPermission('prd.wallet_reconcile.manage')
                || $admin->hasAdminPermission('prd.wallet_adjust.manage');
        }

        return true;
    }

    /**
     * @param list<array{key: string, value: mixed}> $items
     */
    public static function validateItems(array $items): void
    {
        $values = [];
        foreach ($items as $index => $item) {
            $key = (string) $item['key'];
            if (LotterySettings::isEnvLocked($key)) {
                throw ValidationException::withMessages([
                    "items.$index.key" => ['该参数由服务器环境变量配置，不能在后台修改。'],
                ]);
            }

            if (! in_array($key, self::WALLET_LIMIT_KEYS, true)) {
                continue;
            }

            $value = $item['value'];
            if (! is_int($value) || $value < 1) {
                throw ValidationException::withMessages([
                    "items.$index.value" => ['钱包转账限额必须是大于等于 1 的整数最小货币单位。'],
                ]);
            }

            $values[$key] = $value;
        }

        self::validateWalletRange($values, 'wallet.transfer_in_min_minor', 'wallet.transfer_in_max_minor');
        self::validateWalletRange($values, 'wallet.transfer_out_min_minor', 'wallet.transfer_out_max_minor');
    }

    /**
     * @param array<string, int> $values
     */
    private static function validateWalletRange(array $values, string $minKey, string $maxKey): void
    {
        $min = $values[$minKey] ?? max(1, (int) LotterySettings::get($minKey, 1));
        $max = $values[$maxKey] ?? max(1, (int) LotterySettings::get($maxKey, 1));

        if ($max >= $min) {
            return;
        }

        throw ValidationException::withMessages([
            'items' => ['钱包转账最大金额不能小于最小金额。'],
        ]);
    }
}
