"use client";

import type { LoginStatus } from "@/data/dto/auth";
import { ROUTE_BUILDERS } from "@/router/routes";
import { AppEnvUtil, BrowserDetector } from "@/utils";

export interface ExternalBrowserPromptState {
  hasInitialized: boolean;
  isLoading: boolean;
  loginStatus: LoginStatus;
}

export function deriveIsGuest(loginStatus: LoginStatus): boolean {
  return loginStatus === "guest";
}

export function isChatDevelopmentEnvironment(): boolean {
  return AppEnvUtil.isDevelopment();
}

export function shouldStartExternalBrowserPrompt({
  hasInitialized,
  isLoading,
  loginStatus,
}: ExternalBrowserPromptState): boolean {
  if (!hasInitialized || isLoading) return false;
  return (
    isChatDevelopmentEnvironment() ||
    (loginStatus === "facebook" && BrowserDetector.isInAppBrowser())
  );
}

export function getChatPaywallSubscriptionUrl(): string {
  return ROUTE_BUILDERS.subscription("vip", {
    returnTo: "chat",
  });
}

export function getChatCreditsTopUpSubscriptionUrl(): string {
  return ROUTE_BUILDERS.subscription("topup", {
    returnTo: "chat",
  });
}

export function getInsufficientCreditsSubscriptionType(
  isVip: boolean,
): "vip" | "topup" {
  return isVip ? "topup" : "vip";
}

export function getChatPaywallNavigationUrl(
  loginStatus: LoginStatus,
  type: "vip" | "topup" = "vip",
): string {
  const subscriptionUrl =
    type === "topup"
      ? getChatCreditsTopUpSubscriptionUrl()
      : getChatPaywallSubscriptionUrl();
  if (deriveIsGuest(loginStatus)) {
    return ROUTE_BUILDERS.authWithRedirect(subscriptionUrl);
  }
  return subscriptionUrl;
}
