const KEY = 'haixun.publish_persona_by_account'

type PersonaByAccount = Record<string, string>

function readMap(): PersonaByAccount {
  try {
    const raw = localStorage.getItem(KEY)
    if (!raw) return {}
    const parsed = JSON.parse(raw) as PersonaByAccount
    return parsed && typeof parsed === 'object' ? parsed : {}
  } catch {
    return {}
  }
}

function writeMap(map: PersonaByAccount) {
  localStorage.setItem(KEY, JSON.stringify(map))
}

export function getLastPublishPersonaId(accountId: string): string {
  if (!accountId) return ''
  return readMap()[accountId] ?? ''
}

export function setLastPublishPersonaId(accountId: string, personaId: string) {
  if (!accountId) return
  const map = readMap()
  if (!personaId) {
    delete map[accountId]
  } else {
    map[accountId] = personaId
  }
  writeMap(map)
}