local addonName, addonTable = ...

-- ------------------------------------------------------------------------- --
-- SCORCHED EARTH CONFIGURATION
-- ------------------------------------------------------------------------- --
local TARGET_VERSION = 21

-- ------------------------------------------------------------------------- --
-- DATABASE SANITIZER
-- ------------------------------------------------------------------------- --
local CleanerFrame = CreateFrame("Frame")
CleanerFrame:RegisterEvent("ADDON_LOADED")

CleanerFrame:SetScript("OnEvent", function(self, event, arg1)
    -- Only run this when YOUR addon is loaded
    if event == "ADDON_LOADED" and arg1 == addonName then
        
        -- 1. Check if the Primary DB exists; if not, create it so we can set the version
        if _G["GRS_DB"] == nil then _G["GRS_DB"] = {} end
        
        local db = _G["GRS_DB"]
        local currentVer = tonumber(db.version) or 0
        
        -- 2. Version Check
        -- Logic: "Is the current DB version 21 or higher? no, wipe DB's, if yes, remain as is."
        if currentVer < TARGET_VERSION then
            
            local reason = "Protocol Upgrade ("..tostring(currentVer).." < "..tostring(TARGET_VERSION)..")"
            if currentVer == 0 then reason = "New Installation" end

            print("|cffFF0000[GRS]:|r Critical Protocol Update: [" .. reason .. "]")
            print("|cffFF0000[GRS]:|r Standardizing Database Keys to Name-Realm format...")

            -- 3. THE WIPE (Scorched Earth)
            
            -- Wipe Main DB
            if not _G["GRS_DB"] then _G["GRS_DB"] = {} end
            table.wipe(_G["GRS_DB"])
            _G["GRS_DB"].version = TARGET_VERSION 
            
            -- Wipe History
            if _G["GRS_HistoryDB"] then table.wipe(_G["GRS_HistoryDB"]) else _G["GRS_HistoryDB"] = {} end
            
            -- Wipe Identity
            if _G["GRS_IdentityDB"] then table.wipe(_G["GRS_IdentityDB"]) else _G["GRS_IdentityDB"] = {} end
            _G["GRS_IdentityDB"].mains = {}
            _G["GRS_IdentityDB"].alts = {}
            _G["GRS_IdentityDB"].times = {}

            -- Wipe Raid Roster
            if _G["GRS_RaidRosterDB"] then table.wipe(_G["GRS_RaidRosterDB"]) else _G["GRS_RaidRosterDB"] = {} end

            -- Wipe Inspection DB
            if _G["GRS_InspectionDB"] then table.wipe(_G["GRS_InspectionDB"]) else _G["GRS_InspectionDB"] = {} end

            print("|cff00FF00[GRS]:|r Migration Complete. Database Version: " .. TARGET_VERSION)
        end

        self:UnregisterEvent("ADDON_LOADED")
    end
end)