local BLOCKED_AMMOMAKER_COMMANDS = {
    returnCasingsOnAttack = true,
    incrementSpendtRoundCount = true,
    returnCasingsOnReload = true,
}

local function isPatchToggleEnabled()
    local vars = SandboxVars and SandboxVars.OpinionatedFirearms
    if vars and vars.HandleHotBrassCasingSpawnUseAmmoMaker ~= nil then
        return vars.HandleHotBrassCasingSpawnUseAmmoMaker == true
    end

    -- Backward compatibility for existing worlds.
    if vars and vars.HBVCEFAmmoMakerPatch ~= nil then
        return vars.HBVCEFAmmoMakerPatch == true
    end

    return true
end

local function shouldBlockAmmoMakerCasingCommands()
    return isPatchToggleEnabled()
end

local function getModuleAndCommand(...)
    local argc = select("#", ...)
    if argc < 2 then
        return nil, nil
    end

    local firstArg = select(1, ...)
    if type(firstArg) == "string" then
        return firstArg, select(2, ...)
    end

    if argc >= 3 then
        return select(2, ...), select(3, ...)
    end

    return nil, nil
end

local function installCommandGate()
    if _G.OpinionatedFirearms_AmmoMakerCommandGateInstalled then
        return true
    end

    if type(sendClientCommand) ~= "function" then
        return false
    end

    _G.OpinionatedFirearms_AmmoMakerCommandGateInstalled = true
    _G.OpinionatedFirearms_OriginalSendClientCommand = sendClientCommand

    sendClientCommand = function(...)
        local module, command = getModuleAndCommand(...)
        if module == "ammomaker" and BLOCKED_AMMOMAKER_COMMANDS[command] and shouldBlockAmmoMakerCasingCommands() then
            return
        end

        return _G.OpinionatedFirearms_OriginalSendClientCommand(...)
    end

    return true
end

local function ensureGateOnTick()
    if installCommandGate() then
        Events.OnTick.Remove(ensureGateOnTick)
    end
end

if not installCommandGate() then
    Events.OnTick.Add(ensureGateOnTick)
end
