import { UsaHomeStationErrorCode } from './usa-home-station-error.constants';

export type UsaHomeStationErrorPayload = {
  maxMachinesAllowed?: number;
  downlineUsersCount?: number;
  pastPurchasedQuantity?: number;
  cartQuantity?: number;
  totalRequestedQuantity?: number;
};

type ApiErrorShape = {
  code?: string;
  msg?: string;
  message?: string;
  data?: UsaHomeStationErrorPayload;
  error?: UsaHomeStationErrorPayload;
  body?: {
    code?: string;
    msg?: string;
    message?: string;
    data?: UsaHomeStationErrorPayload;
    error?: UsaHomeStationErrorPayload;
  };
};

type TranslateFn = (
  key: string,
  params?: Record<string, string | number>,
) => string;

/**
 * Maps US Nx1 Home Station API error codes to i18n messages.
 * Falls back to API msg when code is unknown.
 */
export function resolveUsaHomeStationErrorMessage(
  error: unknown,
  translate: TranslateFn,
): string {
  const err = error as ApiErrorShape;
  const code = err?.body?.code ?? err?.code;
  const payload = (err?.body?.data ??
    err?.body?.error ??
    err?.data ??
    err?.error) as UsaHomeStationErrorPayload | undefined;
  const fallback =
    err?.body?.msg ?? err?.body?.message ?? err?.msg ?? err?.message;

  switch (code) {
    case UsaHomeStationErrorCode.QUOTA_EXCEEDED:
      return translate("quotaExceeded", {
        defaultAllowance: 1,
        max: payload?.maxMachinesAllowed ?? 0,
        downline: payload?.downlineUsersCount ?? 0,
        past: payload?.pastPurchasedQuantity ?? 0,
        cart: payload?.cartQuantity ?? 0,
      });
    case UsaHomeStationErrorCode.USER_NOT_FOUND:
      return translate("userNotFound");
    case UsaHomeStationErrorCode.ELIGIBILITY_CHECK_FAILED:
      return translate("eligibilityCheckFailed");
    default:
      return fallback ?? translate("generic");
  }
}
