const KEY = 'zapbot_message_authors';

type MessageAuthorMap = Record<string, string>;

function loadAll(): MessageAuthorMap {
  try {
    const raw = localStorage.getItem(KEY);
    if (!raw) return {};
    return JSON.parse(raw);
  } catch (error) {
    return {};
  }
}

function saveAll(data: MessageAuthorMap) {
  localStorage.setItem(KEY, JSON.stringify(data));
}

function makeKey(chatId: string, messageId: string) {
  return `${chatId}::${messageId}`;
}

export function setMessageAuthor(chatId: string, messageId: string, userId: string) {
  const all = loadAll();
  all[makeKey(chatId, messageId)] = userId;
  saveAll(all);
}

export function getMessageAuthor(chatId: string, messageId: string) {
  const all = loadAll();
  return all[makeKey(chatId, messageId)] || null;
}
