"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 async function openChatInExternalBrowser(): 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;

  if (deviceId && asid) {
    UrlLauncherUtil.openUrlWithExternalBrowser(ROUTES.externalEntry, {
      queryParams: {
        target: "chat",
        device_id: deviceId,
        asid,
        ...(psid ? { psid } : {}),
        ...(avatarUrl ? { avatar_url: avatarUrl } : {}),
      },
    });
    return;
  }

  UrlLauncherUtil.openUrlWithExternalBrowser(ROUTES.splash);
}
