local NS = rawget(_G, "MCDVoiceCooldownNS") or {}
_G.MCDVoiceCooldownNS = NS

NS.Core = NS.Core or {}
NS.Core.Bloodlust = NS.Core.Bloodlust or {}

local Bloodlust = NS.Core.Bloodlust
local CONST = NS.Constants or {}

local EXHAUSTION_IDS = CONST.EXHAUSTION_IDS or { 57723, 57724, 80354, 95809, 160455, 207400, 264689, 390435 }
local EXHAUSTION_DURATION = CONST.EXHAUSTION_DURATION or 600
local FRESH_WINDOW = CONST.FRESH_WINDOW or 5

local customSoundPaths = {}
local lastExpiration = 0

local function SafeNormalize(normalizeSoundPath, path)
    if type(normalizeSoundPath) == "function" then
        return normalizeSoundPath(path)
    end
    return tostring(path or ""):gsub("/", "\\")
end

function Bloodlust:GetRuntimeConfig()
    return {
        customSoundPaths = customSoundPaths,
    }
end

function Bloodlust:Rebuild(db, normalizeSoundPath)
    wipe(customSoundPaths)

    local source = type(db) == "table" and type(db.bloodlustConfig) == "table" and db.bloodlustConfig.customSoundPaths or nil
    if type(source) ~= "table" then
        return false
    end

    for i = 1, 5 do
        customSoundPaths[i] = SafeNormalize(normalizeSoundPath, source[i] or "")
    end
    return true
end

function Bloodlust:PlayNotification(cfg, notifier)
    if notifier and type(notifier.PlayBloodlustNotification) == "function" then
        return notifier:PlayBloodlustNotification(cfg or self:GetRuntimeConfig(), customSoundPaths)
    end
    return false
end

function Bloodlust:CheckExhaustionFresh()
    if not C_UnitAuras or not C_UnitAuras.GetPlayerAuraBySpellID then
        return false, nil
    end

    local now = GetTime()
    for _, spellId in ipairs(EXHAUSTION_IDS) do
        local aura = C_UnitAuras.GetPlayerAuraBySpellID(spellId)
        if aura and aura.expirationTime then
            local remaining = (tonumber(aura.expirationTime) or 0) - now
            if remaining >= (EXHAUSTION_DURATION - FRESH_WINDOW) then
                return true, tonumber(aura.expirationTime) or 0
            end
        end
    end

    return false, nil
end

function Bloodlust:HandleUnitAura(unit, notifier)
    if unit ~= "player" then
        return false
    end

    local isFresh, expirationTime = self:CheckExhaustionFresh()
    if isFresh and expirationTime and expirationTime > 0 and expirationTime ~= lastExpiration then
        lastExpiration = expirationTime
        return self:PlayNotification(nil, notifier)
    end

    return false
end
