--[[
    Core/Config.lua

    Thin, typed access layer over ShinyHunterDB.settings.

    Modules must not read the SavedVariables table directly: going through this
    module keeps the storage shape replaceable and gives us a single place to
    fire change notifications from.
]]

local _, ns = ...

local Config = ns.NewModule("Config")
ns.Config = Config

--- Pushes stored settings into the systems that mirror them in memory.
-- Called during start-up and again after a database reset.
function Config:ApplyStoredSettings()
    if ns.Localization then
        ns.Localization:Apply(self:Get("language") or "auto")
    end
    ns.Debug:SetEnabled(self:Get("debugEnabled"))
    ns.Debug:Log("CONFIG", "settings applied")
end

function Config:OnInitialize()
    self:ApplyStoredSettings()
end

--- @param key string A key of the settings table.
-- @return any The stored value.
function Config:Get(key)
    return ns.Database:GetSettings()[key]
end

--- Stores a setting and notifies listeners.
-- @param key string
-- @param value any
function Config:Set(key, value)
    local settings = ns.Database:GetSettings()

    if settings[key] == value then
        return
    end

    settings[key] = value
    if key == "language" and ns.Localization then
        ns.Localization:Apply(value)
    end
    ns.Debug:Log("CONFIG", "%s = %s", key, tostring(value))
    ns.Events:Send("CONFIG_CHANGED", key, value)
end

--- @return table The stored main window anchor (point, relativePoint, x, y).
function Config:GetWindowPosition()
    return ns.Database:GetSettings().window
end

--- Stores the main window anchor.
function Config:SetWindowPosition(point, relativePoint, x, y)
    local window = ns.Database:GetSettings().window

    window.point = point
    window.relativePoint = relativePoint
    window.x = x
    window.y = y
end
