import type { PersistedRefineSession } from "./types";

const PREFIX = "haixun-refine-session";

function storageKey(topicId: string) {
  return `${PREFIX}-${topicId}`;
}

export function loadPersistedSession(topicId: string): PersistedRefineSession | null {
  if (typeof window === "undefined") return null;
  try {
    const raw = localStorage.getItem(storageKey(topicId));
    if (!raw) return null;
    return JSON.parse(raw) as PersistedRefineSession;
  } catch {
    return null;
  }
}

export function savePersistedSession(session: PersistedRefineSession): void {
  if (typeof window === "undefined") return;
  try {
    localStorage.setItem(storageKey(session.topicId), JSON.stringify(session));
  } catch {
    // quota or private mode — in-memory session still works
  }
}

export function removePersistedSession(topicId: string): void {
  if (typeof window === "undefined") return;
  try {
    localStorage.removeItem(storageKey(topicId));
  } catch {
    // ignore
  }
}

export function listPersistedTopicIds(): string[] {
  if (typeof window === "undefined") return [];
  const ids: string[] = [];
  try {
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (key?.startsWith(`${PREFIX}-`)) {
        ids.push(key.slice(PREFIX.length + 1));
      }
    }
  } catch {
    // ignore
  }
  return ids;
}