"use client";

import { ROUTES } from "@/router/routes";

import { consumePendingChatImageReturn } from "./chat_image_return_session";
import {
  clearPendingChatUnlock,
  peekPendingChatUnlock,
} from "./chat_unlock_session";

export type SubscriptionReturnTo = "chat" | null;

export async function consumeSubscriptionExplicitExitUrl(): Promise<string | null> {
  const pendingImageReturn = await consumePendingChatImageReturn();
  if (pendingImageReturn) return pendingImageReturn.returnUrl;
  const pendingChatUnlock = await peekPendingChatUnlock();
  if (pendingChatUnlock) {
    await clearPendingChatUnlock();
    return pendingChatUnlock.returnUrl;
  }
  return null;
}

export async function peekSubscriptionExplicitExitUrl(): Promise<string | null> {
  const pendingChatUnlock = await peekPendingChatUnlock();
  if (pendingChatUnlock) return pendingChatUnlock.returnUrl;
  return null;
}

export function getSubscriptionFallbackExitUrl(
  returnTo: SubscriptionReturnTo,
): string {
  return returnTo === "chat" ? ROUTES.chat : ROUTES.sidebar;
}

export async function consumeSubscriptionExitUrl(
  returnTo: SubscriptionReturnTo,
): Promise<string> {
  return (
    (await consumeSubscriptionExplicitExitUrl()) ??
    getSubscriptionFallbackExitUrl(returnTo)
  );
}
