-- Central integration flags and helpers for the AA Damage all-in-one build.
-- Runtime modules remain independently namespaced, while AA Damage owns the
-- settings surface and conflict resolution.

AA_DAMAGE_UNIFIED_OPTIONS = true

AAIntegration = AAIntegration or {}

function AAIntegration.isServerVehicle(vehicle)
    return vehicle ~= nil and vehicle.isServer == true
end

function AAIntegration.isAuthorizedSettingsConnection(connection)
    if connection == nil or connection.getIsServer == nil or connection:getIsServer() then
        return true
    end
    if g_currentMission == nil or g_currentMission.userManager == nil then
        return false
    end

    local userId = g_currentMission.userManager:getUserIdByConnection(connection)
    if userId == nil then
        return false
    end

    local masterUserId = g_currentMission.userManager:getMasterUserId()
    if masterUserId ~= nil and userId == masterUserId then
        return true
    end

    local farm = g_farmManager ~= nil and g_farmManager:getFarmByUserId(userId) or nil
    return farm ~= nil and farm.isUserFarmManager ~= nil and farm:isUserFarmManager(userId)
end

function AAIntegration.applyCollisionDamage(vehicle, damage)
    if not AAIntegration.isServerVehicle(vehicle) then
        return false
    end

    local spec = vehicle.spec_AdvancedDamageSystem
    if spec == nil or spec.isExcludedVehicle == true or vehicle.applyInstantDamageToSystem == nil then
        return false
    end

    local amount = math.max(tonumber(damage) or 0, 0)
    if amount <= 0 then
        return false
    end

    -- Collisions primarily affect the chassis. A smaller transmission impact
    -- keeps severe crashes meaningful without bypassing ADS maintenance rules.
    vehicle:applyInstantDamageToSystem(AdvancedDamageSystem.SYSTEMS.CHASSIS, amount)
    vehicle:applyInstantDamageToSystem(AdvancedDamageSystem.SYSTEMS.TRANSMISSION, amount * 0.25)
    if vehicle.updateConditionLevel ~= nil then
        vehicle:updateConditionLevel()
    end

    return true
end
