-----------------------------
-- Saved Variables Updater --
-----------------------------

--- Example Use
-----------------------------

--local updates = {
--    {
--        version = "v-0.9.25-alpha",
--        details = "Added Updates",
--        db = {
--            apply = function()
--            end,
--            revert = function()
--            end,
--        },
--        profile = {
--            apply = function()
--            end,
--            revert = function()
--            end,
--        },
--    },
--};

local AddOnName, nsVars = ...
local ss = nsVars.SS

local updates = {
    {
        version = "v-0.9.25-alpha",
        details = "Pet and additional resource tracking are now account wide",
        global = {
            apply = function()
                if ss.db.track then
                    ss.global.track.additionalResource = ss.global.track.additionalResourc or ss.db.track.additionalResource
                    ss.global.track.pet = ss.global.track.pet or ss.db.track.pet
                end
            end,
            revert = function()
                ss.global.track = nil
            end,
        },
    },
    {
        version = "v-0.9.25-alpha",
        details = "Pet and additional resource tracking are now account wide",
        db = {
            apply = function()
                ss.db.track = nil
            end,
            revert = function()
                if ss.global.track then
                    ss.db.track = ss.db.track or {}
                    ss.db.track.additionalResource = ss.global.track.additionalResource
                    ss.db.track.pet = ss.global.track.pet
                end
            end,
        },
    },
};

local update = function(db, latest)
    -- defaults to 0 to ensure new characters include all updates.
    local currentDB = ss[db].latestUpdate or 0

    if currentDB < latest then
        -- perform updates
        for v = currentDB + 1, latest do
            if updates[v] and updates[v][db] then
                updates[v][db].apply()
                ss[db].latestUpdate = v
            end
        end
    elseif currentDB > latest then
        -- perform reverts
        for v = currentDB, latest + 1, -1 do
            if updates[v] and updates[v][db] then
                updates[v][db].revert()
                ss[db].latestUpdate = v - 1
            end
        end
    end

    if not ss[db].latestUpdate then
        -- Ensure this value gets initialized.
        ss[db].latestUpdate = latest
    end
end

local mtUpdater = {
    update = function()
        -- Update to target versions.
        local version = 2
        update("db",      version)
        update("global",  version)
        update("profile", version)
        update("private", version)
    end,
}

ss["Updater"] = setmetatable({}, { __index = mtUpdater });
