local DR = select(2, ...)

local Identity = {}

local function normalizeDisplayName(name, realm)
  if not name or name == "" then
    return nil
  end

  if name:find("-", 1, true) then
    return name
  end

  local finalRealm = realm
  if not finalRealm or finalRealm == "" then
    finalRealm = GetNormalizedRealmName()
  end

  return string.format("%s-%s", name, finalRealm)
end

function Identity:OnInitialize()
  local db = DR.db.global
  db.identityByGuid = db.identityByGuid or {}
  db.guidByDisplay = db.guidByDisplay or {}
end

function Identity:Bind(guid, displayName)
  if not guid or not displayName then
    return
  end

  DR.db.global.identityByGuid[guid] = displayName
  DR.db.global.guidByDisplay[displayName] = guid
end

function Identity:BuildDisplayName(name, realm)
  return normalizeDisplayName(name, realm)
end

function Identity:NormalizeUnit(unit)
  local guid = UnitGUID(unit)
  if not guid then
    return nil, nil
  end

  local name, realm = UnitName(unit)
  local display = normalizeDisplayName(name, realm)

  self:Bind(guid, display)

  return guid, display
end

function Identity:GetDisplayByGuid(guid)
  return DR.db.global.identityByGuid[guid]
end

function Identity:GetGuidByDisplay(displayName)
  return DR.db.global.guidByDisplay[displayName]
end

DR:RegisterModule("Services.Identity", Identity)
