local function callWithAvailableMoney(screen, callback, ...)
    local mission = screen.currentMission or g_currentMission
    local farm = g_farmManager:getFarmById(mission:getFarmId())
    local missionGetMoney = rawget(mission, "getMoney")
    local farmGetBalance = rawget(farm, "getBalance")
    local farmMoney = farm.money

    mission.getMoney = function()
        return math.huge
    end
    farm.getBalance = function()
        return math.huge
    end
    farm.money = math.huge

    local success, errorMessage = pcall(callback, ...)

    mission.getMoney = missionGetMoney
    farm.getBalance = farmGetBalance
    farm.money = farmMoney

    if not success then
        error(errorMessage)
    end
end

local function hookLeaseButton(self)
    local button = self.leaseButton

    if button == nil or button.leaseCostPreviewInstalled then
        return
    end

    local callback = button.onClickCallback
    if callback == nil then
        return
    end

    button.onClickCallback = function(...)
        return callWithAvailableMoney(self, callback, ...)
    end
    button.leaseCostPreviewInstalled = true

    print("FS25_LeaseCostPreview: hooked leaseButton.onClickCallback")
end

ShopConfigScreen.updateButtons = Utils.appendedFunction(
    ShopConfigScreen.updateButtons,
    hookLeaseButton
)
