--[[ Core/DB.lua — SavedVariables schema + migrations (spec §5.4).
     Version field from day 1; migrations run in order, once. ]]--

local _, ns = ...
ns.DB = {}

local SCHEMA_VERSION = 1

local defaults = {
  version = SCHEMA_VERSION,
  favorites = {},          -- [libraryId] = true
  hidden = {},             -- [libraryId] = true
  settings = {
    minimap = { hide = false },
    cardSize = "M",
    lastFilters = {},
  },
  -- scoreCache intentionally NOT persisted (spec §5.4): ownership changes across sessions
}

-- migrations[n] upgrades version n -> n+1
local migrations = {
  -- [1] = function(db) ... end,
}

local function copyDefaults(src, dst)
  for k, v in pairs(src) do
    if type(v) == "table" then
      if type(dst[k]) ~= "table" then dst[k] = {} end
      copyDefaults(v, dst[k])
    elseif dst[k] == nil then
      dst[k] = v
    end
  end
end

function ns.DB.Init()
  BlueprintBazaarDB = BlueprintBazaarDB or {}
  local db = BlueprintBazaarDB
  db.version = db.version or SCHEMA_VERSION
  while db.version < SCHEMA_VERSION do
    local m = migrations[db.version]
    if m then m(db) end
    db.version = db.version + 1
  end
  copyDefaults(defaults, db)
  db.scoreCache = nil          -- scrub if an old version ever persisted it
  ns.db = db
end
