rSemiTruck = rSemiTruck or {}
rSemiTruck.ArmorSync = rSemiTruck.ArmorSync or {}

local ArmorSync = rSemiTruck.ArmorSync

local function getGlobalFunction(name)
	return rawget(_G, name)
end

function ArmorSync.getRuntimeMode()
	local isClientFn = getGlobalFunction("isClient")
	local isServerFn = getGlobalFunction("isServer")
	local clientMode = type(isClientFn) == "function" and isClientFn() or false
	local serverMode = type(isServerFn) == "function" and isServerFn() or false

	return {
		isClient = clientMode,
		isServer = serverMode,
		isMultiplayer = clientMode or serverMode,
	}
end

function ArmorSync.clampCondition(condition)
	condition = math.floor(tonumber(condition) or 0)
	if condition < 0 then return 0 end
	if condition > 100 then return 100 end
	return condition
end

function ArmorSync.applyVehiclePartCondition(vehicle, part, condition)
	if not vehicle or not part or condition == nil then
		return false
	end

	condition = math.max(0, math.min(100, math.floor((tonumber(condition) or 0) + 0.5)))

	if part.setRandomCondition then
		pcall(function() part:setRandomCondition(nil) end)
	end

	part:setCondition(condition)

	local inventoryItem = part:getInventoryItem()
	if inventoryItem and inventoryItem.setCondition then
		inventoryItem:setCondition(condition)
	end

	if part.doInventoryItemStats then
		pcall(function()
			part:doInventoryItemStats(inventoryItem, part:getMechanicSkillInstaller())
		end)
	end

	pcall(function() vehicle:updatePartStats() end)
	pcall(function() vehicle:updateBulletStats() end)
	pcall(function() vehicle:transmitPartCondition(part) end)
	pcall(function() vehicle:transmitPartItem(part) end)
	pcall(function() vehicle:transmitPartModData(part) end)

	return true
end

function ArmorSync.dispatchRepair(player, vehicle, part, condition, moduleName, commandName)
	if not vehicle or not part or condition == nil then
		return false
	end

	local runtimeMode = ArmorSync.getRuntimeMode()
	local sendClientCommandFn = getGlobalFunction("sendClientCommand")
	if runtimeMode.isClient and runtimeMode.isMultiplayer and type(sendClientCommandFn) == "function" then
		sendClientCommandFn(player, moduleName or "W900", commandName or "applyArmorRepair", {
			vehicle = vehicle:getId(),
			part = part:getId(),
			condition = condition,
		})
		return true
	end

	return ArmorSync.applyVehiclePartCondition(vehicle, part, condition)
end

return ArmorSync