#include "../../config/events.lua"
#include "../../script/helpers/entity.lua"
#include "../../script/helpers/mathfr.lua"

body = nil
disabled = nil
duration = 2

function init()
    body = FindBody()
    dmg_to_player = 0.15
    dmg_to_ai = 0.4
    seen = {}
end

function update(dt)
    if disabled then return end

    if not IsBodyBroken(body) then return end

    duration = duration - dt
    if duration < 0 then disabled = cEntity:EnqueueDeletion() return end

    WatchBodyHit(body)
    if not IsBodyHitted(body) then return end

    for index = 0, GetBodyHitsCount(body) - 1 do
        local other_body, impulse, pos, normal, this_vel, other_vel = GetBodyHit(body, index)
        local veh = GetBodyVehicle(other_body)
        impulse = math.abs(impulse)
        if veh > 0 and HasTag(veh, "customhealth") and impulse >= 15 and not seen[veh] and GetVehicleHealth(veh) > 0 then
            local dmg = math:MapRangeClamped(impulse, 15, 30, 0, GetPlayerVehicle() == veh and dmg_to_player or dmg_to_ai)
            if dmg > 0 then
                TriggerEvent(EVENTS.UPDATE_HEALTH, veh .. ";" .. dmg)
                seen[veh] = true
            end
        end
    end
end
