-- TOG Tools — Name Prefix module (engine)
-- Prepends a configurable nickname prefix to outgoing chat messages.
--
-- Hook strategy (most reliable across all versions):
--   Retail 12.0+  : EventRegistry "ChatFrame.OnEditBoxPreSendText"
--   Classic/older : hooksecurefunc on the global ChatEdit_SendText
--                   (present since Vanilla; more reliable than patching
--                    ChatFrameEditBoxMixin.SendText which is missing on
--                    some Classic builds)
--
-- The hook only modifies editBox:SetText() BEFORE the message is sent.
-- It never calls SendChatMessage directly, avoiding taint.

local _, addon = ...
local gv = addon.gameVersion

local NamePrefix = {}
addon.NamePrefix = NamePrefix

-- ---------------------------------------------------------------------------
-- Internal state
-- ---------------------------------------------------------------------------
local _hooked = false   -- set true once the hook is installed

-- ---------------------------------------------------------------------------
-- Core: decide whether to prefix and do it
-- ---------------------------------------------------------------------------
local function ModifyMessage(editBox)
    local cfg = addon.DB and addon.DB.char.namePrefix
    if not cfg then return end
    if not cfg.enabled then return end

    -- InCombatLockdown guard: SetText taints the protected SendChatMessage
    -- call that follows on some clients. Message still sends as-is.
    if InCombatLockdown() then return end

    local nick = cfg.nickname
    if not nick or nick == "" then return end

    -- Optionally suppress when nickname matches current character name
    if cfg.hideIfCharName then
        local charName = UnitName("player")
        if charName and nick == charName then return end
    end

    local msg = editBox:GetText()
    if not msg or msg == "" then return end

    -- Skip messages starting with "!" (addon commands like !keys)
    if cfg.skipExclamation and string.sub(msg, 1, 1) == "!" then return end

    -- Determine chat type
    local chatType = editBox:GetAttribute("chatType") or editBox.chatType or "SAY"

    local shouldPrefix = false
    if     chatType == "GUILD"         and cfg.guild    then shouldPrefix = true
    elseif chatType == "OFFICER"       and cfg.officer  then shouldPrefix = true
    elseif chatType == "PARTY"         and cfg.party    then shouldPrefix = true
    elseif chatType == "PARTY_LEADER"  and cfg.party    then shouldPrefix = true
    elseif chatType == "RAID"          and cfg.raid     then shouldPrefix = true
    elseif chatType == "RAID_WARNING"  and cfg.raid     then shouldPrefix = true
    elseif chatType == "INSTANCE_CHAT" and cfg.instance then shouldPrefix = true
    elseif chatType == "CHANNEL"       and cfg.channel and cfg.channel ~= "" then
        local channelTarget = editBox:GetAttribute("channelTarget") or editBox.channelTarget
        if channelTarget then
            local _, chname = GetChannelName(channelTarget)
            if chname and strupper(cfg.channel) == strupper(chname) then
                shouldPrefix = true
            end
        end
    end

    if not shouldPrefix then return end

    -- Build prefix from format string (safe substitution)
    local fmt = (cfg.format and cfg.format ~= "") and cfg.format or "(%s): "
    local prefix = string.format(fmt, nick)
    editBox:SetText(prefix .. msg)
end

-- ---------------------------------------------------------------------------
-- Hook installation
-- ---------------------------------------------------------------------------
function NamePrefix:Install()
    if _hooked then return end

    if gv.isRetail120Plus and EventRegistry then
        -- Retail 12.0+: Blizzard fires this event just before SendText reads
        -- the editbox content, giving us a clean slot to inject our prefix.
        EventRegistry:RegisterCallback(
            "ChatFrame.OnEditBoxPreSendText",
            function(_event, editBox)
                local ok, err = pcall(ModifyMessage, editBox)
                if not ok and addon.DB and addon.DB.char.namePrefix.enabled then
                    -- Only surface errors when the feature is active
                    print("|cffFF8000TOGTools|r NamePrefix error: " .. tostring(err))
                end
            end,
            NamePrefix
        )
        _hooked = true
    else
        -- Classic / older Retail: hook the global ChatEdit_SendText which
        -- is called for every chat send across all Classic versions.
        if ChatEdit_SendText then
            hooksecurefunc("ChatEdit_SendText", function(editBox)
                local ok, err = pcall(ModifyMessage, editBox)
                if not ok and addon.DB and addon.DB.char.namePrefix.enabled then
                    print("|cffFF8000TOGTools|r NamePrefix error: " .. tostring(err))
                end
            end)
            _hooked = true
        end
        -- If ChatEdit_SendText is somehow absent, the feature silently
        -- does nothing rather than erroring at startup.
    end
end

function NamePrefix:OnEnable()
    self:Install()
end

-- ---------------------------------------------------------------------------
-- Register as a module (engine only — no tab key; tab is in NamePrefixTab.lua)
-- ---------------------------------------------------------------------------
-- The tab registration lives in GUI/NamePrefixTab.lua which loads after this
-- file and merges its Draw/WINDOW_SIZE into addon.modules["nameprefix"].
addon.modules["nameprefix"] = NamePrefix
