// 对话输入草稿的 localStorage 封装。按用户隔离、按 task 保存；特殊 key
// "__new__" 表示尚未创建 task 的“新对话”入口。
export const NEW_CHAT_DRAFT_ID = "__new__";
const STORAGE_PREFIX = "zcbot.chat-drafts.v1.";
const MAX_DRAFTS = 50;

export function chatDraftStorageKey(userId) {
  return userId ? STORAGE_PREFIX + userId : "";
}

function readAll(storage, userId) {
  const key = chatDraftStorageKey(userId);
  if (!key) return {};
  try {
    const parsed = JSON.parse(storage.getItem(key) || "{}");
    return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
  } catch (_) {
    return {};
  }
}

export function readChatDraft(storage, userId, draftId) {
  const item = readAll(storage, userId)[draftId];
  return item && typeof item.text === "string" ? item.text : "";
}

export function writeChatDraft(storage, userId, draftId, text, now = Date.now()) {
  const key = chatDraftStorageKey(userId);
  if (!key || !draftId) return;
  const drafts = readAll(storage, userId);
  if (!text || !text.trim()) {
    delete drafts[draftId];
  } else {
    drafts[draftId] = { text, updatedAt: now };
  }
  const entries = Object.entries(drafts)
    .sort((a, b) => Number(b[1]?.updatedAt || 0) - Number(a[1]?.updatedAt || 0))
    .slice(0, MAX_DRAFTS);
  try {
    if (entries.length) storage.setItem(key, JSON.stringify(Object.fromEntries(entries)));
    else storage.removeItem(key);
  } catch (_) {
    // 隐私模式、WebView 禁用存储或 quota 满时静默跳过持久化，不阻断输入。
  }
}

export function clearChatDraft(storage, userId, draftId) {
  writeChatDraft(storage, userId, draftId, "");
}
