"use client";

import { AppStorage } from "@/data/storage/app/app_storage";
import { AuthStorage } from "@/data/storage/auth/auth_storage";
import { UserStorage } from "@/data/storage/user/user_storage";
import { ROUTE_BUILDERS, ROUTES } from "@/router/routes";
import { todayString, UrlLauncherUtil } from "@/utils";

export async function resolveExternalBrowserPromptEligibility(): Promise<{
  canShow: boolean;
  today: string;
}> {
  const today = todayString();
  const result = await AppStorage.canShowExternalBrowserDialog(today);
  return {
    canShow: result.success && result.data,
    today,
  };
}

export function recordExternalBrowserPromptShown(
  today: string,
): Promise<unknown> {
  return AppStorage.recordExternalBrowserDialogShown(today);
}

export async function openChatInExternalBrowser(): Promise<void> {
  const authStorage = AuthStorage.getInstance();
  const userStorage = UserStorage.getInstance();
  const [deviceIdR, facebookIdR, avatarUrlR] = await Promise.all([
    authStorage.getDeviceId(),
    authStorage.getFacebookId(),
    userStorage.getAvatarUrl(),
  ]);

  const deviceId = deviceIdR.success ? deviceIdR.data : null;
  const facebookId = facebookIdR.success ? facebookIdR.data : null;
  const avatarUrl = avatarUrlR.success ? avatarUrlR.data : null;

  if (deviceId && facebookId) {
    UrlLauncherUtil.openUrlWithExternalBrowser(
      ROUTE_BUILDERS.chatDeviceId(deviceId),
      {
        queryParams: {
          fbid: facebookId,
          ...(avatarUrl ? { avatarUrl } : {}),
        },
      },
    );
    return;
  }

  UrlLauncherUtil.openUrlWithExternalBrowser(ROUTES.splash);
}

export async function persistExternalBrowserChatDeepLink(input: {
  deviceId: string;
  facebookId?: string | null;
  avatarUrl?: string | null;
}): Promise<void> {
  await AuthStorage.getInstance().setDeviceId(input.deviceId);
  if (input.facebookId && input.facebookId.length > 0) {
    await AuthStorage.getInstance().setFacebookId(input.facebookId);
  }
  if (input.avatarUrl && input.avatarUrl.length > 0) {
    await UserStorage.getInstance().setAvatarUrl(input.avatarUrl);
  }
}
