local DR = select(2, ...)
local constants = DR.Modules["Core.Constants"]

local Compat = {
  migrators = {
    [1] = function(addon)
      addon.db.global.identityByGuid = addon.db.global.identityByGuid or {}
      addon.db.global.guidByDisplay = addon.db.global.guidByDisplay or {}
      addon.db.global.weightLedger = addon.db.global.weightLedger or {}
      addon.db.global.weeklyLedger = addon.db.global.weeklyLedger or { lastResetToken = nil }
      addon.db.global.bossLedger = addon.db.global.bossLedger or {}
      addon.db.global.auditEvents = addon.db.global.auditEvents or {}
      addon.db.global.deferredTrades = addon.db.global.deferredTrades or {}
      addon.db.global.deferredTradeOrder = addon.db.global.deferredTradeOrder or {}
      addon.db.global.commStats = addon.db.global.commStats or {
        sent = 0,
        acked = 0,
        retried = 0,
        dropped = 0,
        duplicates = 0,
      }
      addon.db.global.logs = addon.db.global.logs or {}
    end,
  },
}

function Compat:Run(addon)
  local log = addon.logService and addon.logService:Get("Compat")
  local targetSchema = constants.VERSION.SCHEMA
  local current = tonumber(addon.db.global.schemaVersion or 0) or 0

  while current < targetSchema do
    local nextSchema = current + 1
    local migrator = self.migrators[nextSchema]

    if not migrator then
      if log then
        log:e("Missing migrator", nextSchema)
      end
      break
    end

    local ok, err = pcall(migrator, addon)
    if not ok then
      if log then
        log:e("Migration failed", nextSchema, err)
      end
      break
    end

    addon.db.global.schemaVersion = nextSchema
    current = nextSchema

    if log then
      log:i("Migration applied", nextSchema)
    end
  end

  addon.db.global.protocolVersion = constants.VERSION.PROTOCOL
end

DR:RegisterModule("Core.Compat", Compat)
