import type { LoginStatus } from "@/data/schemas/auth";
import type { UserView } from "@/stores/user/user-view";

export type ProfileUserState = "guest" | "member" | "vip";

export const PROFILE_FALLBACK_USERNAME = "User name";

export interface ProfileUserInput {
  currentUser: UserView | null;
  avatarUrl: string | null;
  creditBalance?: number | null;
}

export interface ProfileWalletView {
  creditBalance: number;
  dailyFreeChatLimit: number;
  dailyFreeChatRemaining: number;
  dailyFreePrivateLimit: number;
  dailyFreePrivateRemaining: number;
}

export interface ProfileViewModel {
  state: ProfileUserState;
  name: string;
  avatarUrl: string | null;
  isInitializingUser: boolean;
  wallet: ProfileWalletView;
  canActivateVip: boolean;
  canShowSettings: boolean;
}

export function getProfileViewModel({
  loginStatus,
  user,
}: {
  loginStatus: LoginStatus;
  user: ProfileUserInput;
}): ProfileViewModel {
  const state = getProfileUserState(loginStatus, user.currentUser);

  return {
    state,
    name: user.currentUser?.username ?? PROFILE_FALLBACK_USERNAME,
    avatarUrl: user.avatarUrl,
    isInitializingUser: state !== "guest" && user.currentUser == null,
    wallet: getProfileWalletView(user),
    canActivateVip: state !== "vip",
    canShowSettings: state !== "guest",
  };
}

export function getProfileUserState(
  loginStatus: LoginStatus,
  currentUser: UserView | null,
): ProfileUserState {
  if (loginStatus === "notLoggedIn" || loginStatus === "guest") {
    return "guest";
  }
  return currentUser?.isVip === true ? "vip" : "member";
}

export function getProfileWalletView(
  user: ProfileUserInput,
): ProfileWalletView {
  const currentUser = user.currentUser;

  return {
    creditBalance: normalizeProfileCount(user.creditBalance),
    dailyFreeChatLimit: normalizeProfileCount(currentUser?.dailyFreeChatLimit),
    dailyFreeChatRemaining: normalizeProfileCount(
      currentUser?.dailyFreeChatRemaining,
    ),
    dailyFreePrivateLimit: normalizeProfileCount(
      currentUser?.dailyFreePrivateLimit,
    ),
    dailyFreePrivateRemaining: normalizeProfileCount(
      currentUser?.dailyFreePrivateRemaining,
    ),
  };
}

export function normalizeProfileCount(value: number | null | undefined): number {
  if (typeof value !== "number" || !Number.isFinite(value)) return 0;
  return Math.max(0, Math.trunc(value));
}
