"use client";

import { AuthStorage } from "@/data/storage/auth/auth_storage";
import { UserStorage } from "@/data/storage/user/user_storage";
import type { PendingChatPromotionType } from "@/data/storage/navigation";
import type { LoginStatus } from "@/data/dto/auth";
import { ROUTES } from "@/router/routes";
import {
  buildTipCoffeePath,
  DEFAULT_TIP_COFFEE_TYPE,
  resolveTipCoffeeType,
} from "@/lib/tip/tip_coffee";

export type ExternalEntryTarget =
  | typeof ROUTES.chat
  | typeof ROUTES.tip
  | typeof ROUTES.privateRoom;

export interface ExternalEntryPayload {
  deviceId?: string | null;
  asid?: string | null;
  psid?: string | null;
  avatarUrl?: string | null;
}

export interface ExternalEntryTargetInput {
  target?: string | null;
}

export interface ExternalEntryDestinationInput extends ExternalEntryTargetInput {
  coffeeType?: string | null;
}

export interface ExternalEntryPromotionInput {
  mode?: string | null;
  promotionType?: string | null;
}

export interface ExternalFacebookIdentityBindingInput {
  hasInitialized: boolean;
  isLoading: boolean;
  loginStatus: LoginStatus;
  asid?: string | null;
  psid?: string | null;
}

export function shouldBindExternalFacebookIdentity({
  hasInitialized,
  isLoading,
  loginStatus,
  asid,
  psid,
}: ExternalFacebookIdentityBindingInput): boolean {
  const isRealUser =
    loginStatus === "email" ||
    loginStatus === "google" ||
    loginStatus === "facebook";
  return (
    hasInitialized &&
    !isLoading &&
    isRealUser &&
    (hasValue(asid) || hasValue(psid))
  );
}

export function resolveExternalEntryPromotionType({
  mode,
  promotionType,
}: ExternalEntryPromotionInput): PendingChatPromotionType | null {
  if (mode?.trim().toLowerCase() !== "promotion") return null;

  const normalizedType = promotionType?.trim().toLowerCase();
  if (
    normalizedType === "voice" ||
    normalizedType === "image" ||
    normalizedType === "private"
  ) {
    return normalizedType;
  }
  return null;
}

export function resolveExternalEntryTarget({
  target,
}: ExternalEntryTargetInput): ExternalEntryTarget {
  return resolveTarget(target) ?? ROUTES.chat;
}

export function resolveExternalEntryDestination({
  target,
  coffeeType,
}: ExternalEntryDestinationInput): string {
  const resolvedTarget = resolveExternalEntryTarget({ target });
  if (resolvedTarget !== ROUTES.tip) return resolvedTarget;

  return buildTipCoffeePath(
    resolveTipCoffeeType(coffeeType) ?? DEFAULT_TIP_COFFEE_TYPE,
  );
}

export async function persistExternalEntryPayload({
  deviceId,
  asid,
  psid,
  avatarUrl,
}: ExternalEntryPayload): Promise<void> {
  const authStorage = AuthStorage.getInstance();
  const userStorage = UserStorage.getInstance();
  const tasks: Promise<unknown>[] = [];

  if (hasValue(deviceId)) {
    tasks.push(authStorage.setDeviceId(deviceId));
  }
  if (hasValue(asid)) {
    tasks.push(authStorage.setAsid(asid));
  }
  if (hasValue(psid)) {
    tasks.push(authStorage.setPsid(psid));
  }
  if (hasValue(avatarUrl)) {
    tasks.push(userStorage.setAvatarUrl(avatarUrl));
  }

  await Promise.all(tasks);
}

function resolveTarget(
  value: string | null | undefined,
): ExternalEntryTarget | null {
  if (!value) return null;
  const target = value.trim().toLowerCase();

  if (target === "chat") return ROUTES.chat;
  if (target === "tip") return ROUTES.tip;
  if (target === "private-room") return ROUTES.privateRoom;

  return null;
}

function hasValue(value: string | null | undefined): value is string {
  return typeof value === "string" && value.trim().length > 0;
}
