-- ============================================================
-- Asylum Compagnon — GearCompassDatabase.lua
-- Migration ciblée et paramètres persistants minimaux de l'export GearCompass.
-- ============================================================

local _, NS = ...

local DB = {}
NS.GearCompassDB = DB

local DEFAULT_SETTINGS = {
    includeEquipped = true,
    includeBags = true,
    includeNonEquippable = false,
}
DB.DEFAULT_SETTINGS = DEFAULT_SETTINGS

local debugEnabled = false
local LEGACY_DB_KEY = "tank" .. "gear"

local function IsCurrentExport(value)
    return type(value) == "string"
        and value:find('"export_type":"gearcompass"', 1, true) ~= nil
        and value:find('"adjustments":', 1, true) ~= nil
        and value:find('"excluded_before_resolution":', 1, true) ~= nil
end

function DB.Migrate(root)
    if type(root) ~= "table" then return nil, "DB_ROOT_MISSING" end
    -- Reprend une seule fois les préférences enregistrées sous l'ancien nom,
    -- puis supprime cette clé afin que seules les données GearCompass subsistent.
    if type(root.gearcompass) ~= "table" then
        root.gearcompass = type(root[LEGACY_DB_KEY]) == "table" and root[LEGACY_DB_KEY] or {}
    end
    root[LEGACY_DB_KEY] = nil
    local gearcompass = root.gearcompass

    if type(gearcompass.settings) ~= "table" then gearcompass.settings = {} end
    for key, value in pairs(DEFAULT_SETTINGS) do
        if gearcompass.settings[key] == nil then gearcompass.settings[key] = value end
    end
    for key in pairs(gearcompass.settings) do
        if DEFAULT_SETTINGS[key] == nil then gearcompass.settings[key] = nil end
    end

    -- Les exports antérieurs n'ont ni la nouvelle sémantique des statistiques
    -- ni adjustments.ring_enchants : ne jamais les réafficher comme actuels.
    if gearcompass.lastExport ~= nil and not IsCurrentExport(gearcompass.lastExport) then
        gearcompass.lastExport = nil
    end

    -- Périmètre persistant strict : settings + lastExport, rien d'autre.
    for key in pairs(gearcompass) do
        if key ~= "settings" and key ~= "lastExport" then gearcompass[key] = nil end
    end
    return gearcompass
end

function DB.Init()
    if not NS.db then return nil end
    return DB.Migrate(NS.db)
end

function DB.Get()
    return (NS.db and NS.db.gearcompass) or DB.Init()
end

function DB.GetSettings()
    local data = DB.Get()
    return data and data.settings or DEFAULT_SETTINGS
end

function DB.IsDebugEnabled()
    return debugEnabled
end

function DB.ToggleDebug()
    debugEnabled = not debugEnabled
    return debugEnabled
end

function NS.GearCompassDebug(message, ...)
    if not debugEnabled then return end
    local text = tostring(message or "")
    if select("#", ...) > 0 then
        local ok, formatted = pcall(string.format, text, ...)
        if ok then text = formatted end
    end
    if NS.Msg then NS.Msg("|cff8b8fa3[GearCompass]|r " .. text) end
end

function DB.SelfTestMigration()
    local oldExport = '{"export_type":"' .. LEGACY_DB_KEY .. '","bank":{},"items":[]}'
    local currentExport = '{"adjustments":{"ring_enchants":{"enabled":true,"slots":2}},"export_type":"gearcompass","scan":{"excluded_before_resolution":{"total":0}}}'
    local fake = {}
    fake[LEGACY_DB_KEY] = {
        settings = { includeBags = false, includeBank = true, unknown = true },
        bankCache = {},
        lastExport = oldExport,
        lastExportAt = 123,
        lastExportSummary = {},
        storageVersion = 2,
        debug = true,
    }
    local data = DB.Migrate(fake)
    local exactRoot, exactSettings = true, true
    for key in pairs(data or {}) do
        if key ~= "settings" and key ~= "lastExport" then exactRoot = false end
    end
    for key in pairs(data and data.settings or {}) do
        if DEFAULT_SETTINGS[key] == nil then exactSettings = false end
    end
    local ok = data and data.settings.includeBags == false
        and data.settings.includeEquipped == true
        and data.settings.includeBank == nil
        and data.bankCache == nil
        and data.lastExport == nil
        and data.lastExportSummary == nil
        and fake[LEGACY_DB_KEY] == nil
        and fake.gearcompass == data
        and exactRoot and exactSettings
    data.lastExport = currentExport
    DB.Migrate(fake)
    ok = ok and data.lastExport == currentExport
    return not not ok, fake
end
