"use client";

import { AuthStorage } from "@/data/storage/auth/auth_storage";
import { UserStorage } from "@/data/storage/user/user_storage";
import { ROUTES } from "@/router/routes";
import { UrlLauncherUtil } from "@/utils/url-launcher-util";

export interface OpenChatInExternalBrowserInput {
  characterSlug?: string;
}

export async function openChatInExternalBrowser({
  characterSlug,
}: OpenChatInExternalBrowserInput = {}): Promise<void> {
  const authStorage = AuthStorage.getInstance();
  const userStorage = UserStorage.getInstance();
  const [deviceIdR, asidR, psidR, avatarUrlR] =
    await Promise.all([
      authStorage.getDeviceId(),
      authStorage.getAsid(),
      authStorage.getPsid(),
      userStorage.getAvatarUrl(),
    ]);

  const deviceId = deviceIdR.success ? deviceIdR.data : null;
  const asid = asidR.success ? asidR.data : null;
  const psid = psidR.success ? psidR.data : null;
  const avatarUrl = avatarUrlR.success ? avatarUrlR.data : null;

  UrlLauncherUtil.openUrlWithExternalBrowser(ROUTES.externalEntry, {
    queryParams: {
      target: "chat",
      favorite: "1",
      ...(characterSlug ? { character: characterSlug } : {}),
      ...(deviceId ? { device_id: deviceId } : {}),
      ...(asid ? { asid } : {}),
      ...(psid ? { psid } : {}),
      ...(avatarUrl ? { avatar_url: avatarUrl } : {}),
    },
  });
}
