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

local _, NS = ...

local DB = {}
NS.TankgearDB = DB

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

local debugEnabled = false

local function IsCurrentExport(value)
    return type(value) == "string"
        and value:find('"export_type":"tankgear"', 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
    if type(root.tankgear) ~= "table" then root.tankgear = {} end
    local tankgear = root.tankgear

    if type(tankgear.settings) ~= "table" then tankgear.settings = {} end
    for key, value in pairs(DEFAULT_SETTINGS) do
        if tankgear.settings[key] == nil then tankgear.settings[key] = value end
    end
    for key in pairs(tankgear.settings) do
        if DEFAULT_SETTINGS[key] == nil then tankgear.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 tankgear.lastExport ~= nil and not IsCurrentExport(tankgear.lastExport) then
        tankgear.lastExport = nil
    end

    -- Périmètre persistant strict : settings + lastExport, rien d'autre.
    for key in pairs(tankgear) do
        if key ~= "settings" and key ~= "lastExport" then tankgear[key] = nil end
    end
    return tankgear
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.tankgear) 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.TankgearDebug(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[Tankgear]|r " .. text) end
end

function DB.SelfTestMigration()
    local oldExport = '{"export_type":"tankgear","bank":{},"items":[]}'
    local currentExport = '{"adjustments":{"ring_enchants":{"enabled":true,"slots":2}},"export_type":"tankgear","scan":{"excluded_before_resolution":{"total":0}}}'
    local fake = {
        tankgear = {
            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 exactRoot and exactSettings
    data.lastExport = currentExport
    DB.Migrate(fake)
    ok = ok and data.lastExport == currentExport
    return not not ok, fake
end
