const CODEX_LIVE_DRAFT_STORAGE_KEY = 'codex-live:draft-bridge';

export type CodexLiveDraftPayload = {
  text: string;
  source: string;
  createdAt: string;
  autoSend?: boolean;
  sendMode?: 'queue' | 'direct';
};

export function stashCodexLiveDraft(payload: CodexLiveDraftPayload) {
  if (typeof window === 'undefined') {
    return false;
  }

  const text = payload.text.trim();
  if (!text) {
    return false;
  }

  window.sessionStorage.setItem(
    CODEX_LIVE_DRAFT_STORAGE_KEY,
    JSON.stringify({
      text,
      source: payload.source.trim() || 'unknown',
      createdAt: payload.createdAt.trim() || new Date().toISOString(),
      autoSend: payload.autoSend === true,
      sendMode: payload.sendMode === 'direct' ? 'direct' : 'queue',
    }),
  );
  return true;
}

export function consumeCodexLiveDraft() {
  if (typeof window === 'undefined') {
    return null;
  }

  const raw = window.sessionStorage.getItem(CODEX_LIVE_DRAFT_STORAGE_KEY);
  if (!raw) {
    return null;
  }

  window.sessionStorage.removeItem(CODEX_LIVE_DRAFT_STORAGE_KEY);

  try {
    const payload = JSON.parse(raw) as Partial<CodexLiveDraftPayload>;
    const text = typeof payload.text === 'string' ? payload.text.trim() : '';

    if (!text) {
      return null;
    }

    return {
      text,
      source: typeof payload.source === 'string' ? payload.source.trim() || 'unknown' : 'unknown',
      createdAt:
        typeof payload.createdAt === 'string' && payload.createdAt.trim()
          ? payload.createdAt.trim()
          : new Date().toISOString(),
      autoSend: payload.autoSend === true,
      sendMode: payload.sendMode === 'direct' ? 'direct' : 'queue',
    } satisfies CodexLiveDraftPayload;
  } catch {
    return null;
  }
}
