-- TOG Tools — Logs (outer container + sub-category registry)
--
-- The Logs tab is a NEXUS — its body is a nested AceGUI TabGroup whose
-- sub-tabs are populated from `addon.logCategories`. This file owns:
--   * the outer tab registration (`addon.modules["logs"]`)
--   * the sub-category registry
--   * `addon:IsLogCategoryEnabled(subKey)` — gate helper for sub-engines
--   * `Logs:PruneEntries(entries)` — retention prune called by sub-engines
--
-- Sub-engines (Mail / Trade / Guild) self-register at file-load time:
--     addon.logCategories["mail"] = MailLog
-- Each entry should expose:
--     subKey     string   internal key matching the inner tab value
--     label      string   strip label
--     configKey  string   db.global section holding `enabled` + data
--     Draw(container)     AceGUI container for the sub-tab body
-- The sub-tab Draw is merged in by the corresponding GUI/<Name>SubTab.lua.

local _, addon = ...

local Logs = {}
addon.modules["logs"] = Logs

addon.logCategories = addon.logCategories or {}

-- Returns true iff the Logs master toggle is on AND the per-category
-- toggle is on. Sub-engines call this from every event hook so disabling
-- either flag silently kills the work. Defaults to true for unknown
-- categories so freshly-registered sub-engines aren't accidentally
-- suppressed before they declare a configKey.
function addon:IsLogCategoryEnabled(subKey)
    if not (self.DB and self.DB.global) then return true end
    if not self:IsModuleEnabled("logs") then return false end
    local cat = addon.logCategories and addon.logCategories[subKey]
    if not cat then return true end
    local section = self.DB.global[cat.configKey or ""]
    if not section then return true end
    if section.enabled == nil then return true end
    return section.enabled and true or false
end

-- Drop entries older than db.global.logs.retentionDays from the head of
-- the list. `entries` is expected to be roughly chronological (sub-engines
-- append on capture, so head = oldest); we walk from the front while
-- entries are expired. retentionDays == 0 disables pruning entirely.
function Logs:PruneEntries(entries)
    if not entries or not entries[1] then return end
    local cfg = addon.DB and addon.DB.global and addon.DB.global.logs
    local days = cfg and cfg.retentionDays or 90
    if days <= 0 then return end
    local cutoff = (GetServerTime() or time()) - days * 86400
    while entries[1] and (entries[1].ts or 0) < cutoff do
        table.remove(entries, 1)
    end
end

function Logs:OnEnable()
    -- No engine hooks here; sub-engines wire their own. This hook exists
    -- for module-pattern consistency.
end
