const CURRENT_SESSION_KEY = "codexRemote.currentSession";
const CURRENT_CONTEXT_KEY = "codexRemote.currentContext";
const CURRENT_VIEW_KEY = "codexRemote.currentView";
const APP_VIEWS = new Set(["threads", "chat", "new", "settings"]);

export function readSavedSession(storage = safeStorage()) {
  try {
    const raw = storage?.getItem(CURRENT_SESSION_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw);
    return typeof parsed.sessionId === "string" && parsed.sessionId.trim()
      ? { sessionId: parsed.sessionId }
      : null;
  } catch {
    return null;
  }
}

export function writeSavedSession(storage = safeStorage(), session) {
  if (!storage || typeof session?.id !== "string" || !session.id.trim()) return;
  storage.setItem(CURRENT_SESSION_KEY, JSON.stringify({ sessionId: session.id }));
}

export function clearSavedSession(storage = safeStorage()) {
  storage?.removeItem(CURRENT_SESSION_KEY);
}

export function readSavedContext(storage = safeStorage()) {
  try {
    const raw = storage?.getItem(CURRENT_CONTEXT_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw);
    return {
      accountId: cleanString(parsed.accountId),
      workspaceId: cleanString(parsed.workspaceId)
    };
  } catch {
    return null;
  }
}

export function writeSavedContext(storage = safeStorage(), context = {}) {
  if (!storage) return;
  const accountId = cleanString(context.accountId);
  const workspaceId = cleanString(context.workspaceId);
  storage.setItem(CURRENT_CONTEXT_KEY, JSON.stringify({ accountId, workspaceId }));
}

export function readSavedView(storage = safeStorage()) {
  try {
    const view = storage?.getItem(CURRENT_VIEW_KEY);
    return APP_VIEWS.has(view) ? view : "threads";
  } catch {
    return "threads";
  }
}

export function writeSavedView(storage = safeStorage(), view) {
  if (!storage || !APP_VIEWS.has(view)) return;
  storage.setItem(CURRENT_VIEW_KEY, view);
}

function safeStorage() {
  return typeof window === "undefined" ? null : window.localStorage;
}

function cleanString(value) {
  return typeof value === "string" && value.trim() ? value.trim() : "";
}
