"use client";

const STORAGE_KEY = "cozsweet.chat.pendingImageReturn";
const MAX_AGE_MS = 30 * 60 * 1000;

export interface PendingChatImageReturn {
  reason: "image_paywall";
  messageId: string;
  returnUrl: string;
  createdAt: number;
}

export function savePendingChatImageReturn(input: {
  messageId: string;
  returnUrl: string;
}): void {
  if (typeof window === "undefined") return;
  const payload: PendingChatImageReturn = {
    reason: "image_paywall",
    messageId: input.messageId,
    returnUrl: input.returnUrl,
    createdAt: Date.now(),
  };
  window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(payload));
}

export function consumePendingChatImageReturn(): PendingChatImageReturn | null {
  if (typeof window === "undefined") return null;

  const raw = window.sessionStorage.getItem(STORAGE_KEY);
  window.sessionStorage.removeItem(STORAGE_KEY);
  if (!raw) return null;

  try {
    const value = JSON.parse(raw) as Partial<PendingChatImageReturn>;
    if (value.reason !== "image_paywall") return null;
    if (typeof value.messageId !== "string" || value.messageId.length === 0) {
      return null;
    }
    if (typeof value.returnUrl !== "string" || value.returnUrl.length === 0) {
      return null;
    }
    if (typeof value.createdAt !== "number") return null;
    if (Date.now() - value.createdAt > MAX_AGE_MS) return null;

    return {
      reason: value.reason,
      messageId: value.messageId,
      returnUrl: value.returnUrl,
      createdAt: value.createdAt,
    };
  } catch {
    return null;
  }
}
