const ERROR_CODE_KEYS = Object.freeze({
  account_locked: "errors.accountLocked",
  app_inactive: "errors.appInactive",
  invalid_credentials: "auth.invalidCredentials",
  rate_limited: "errors.rateLimited",
  too_many_requests: "errors.rateLimited"
});

export class ExternalUiError extends Error {
  constructor(translationKey) {
    super(translationKey);
    this.name = "ExternalUiError";
    this.translationKey = translationKey;
  }
}

export function externalUiError(translationKey) {
  return new ExternalUiError(translationKey);
}

export function translateExternalError(error, t, fallbackKey = "errors.requestFailed") {
  if (error?.translationKey) {
    return t(error.translationKey);
  }
  const code = String(error?.code || "").trim().toLowerCase().replace(/[.-]/g, "_");
  if (ERROR_CODE_KEYS[code]) {
    return t(ERROR_CODE_KEYS[code]);
  }
  if (error?.status === 401) {
    return t("errors.unauthorized");
  }
  if (error?.status === 403) {
    return t("errors.forbidden");
  }
  if (error?.status === 404) {
    return t("errors.notFound");
  }
  if (error?.status === 409) {
    return t("errors.conflict");
  }
  if (error?.status === 413) {
    return t("errors.tooLarge");
  }
  if (error?.status === 429) {
    return t("errors.rateLimited");
  }
  if (Number(error?.status) >= 500) {
    return t("errors.server");
  }
  return t(fallbackKey);
}
