/**
 * Maps thrown values to short, user-facing text for API clients.
 * Does not change response shapes — use the returned string as `message` / `error` fields only.
 */

function joinValidationMessages(errors: Record<string, { message?: string }>): string {
  const parts = Object.values(errors)
    .map(v =>
      typeof v?.message === 'string' ? simplifyMongoosePathMessage(v.message) : ''
    )
    .filter(Boolean);
  return parts.length ? parts.join(' ') : '';
}

function simplifyMongoosePathMessage(m: string): string {
  return m
    .replace(/^Path `/, '')
    .replace(/` is required\.?$/, ' is required.')
    .replace(/` \(.*$/, '')
    .trim();
}

function isLikelyStackOrInternal(msg: string): boolean {
  return (
    msg.includes('\n    at ') ||
    msg.includes('    at ') ||
    /^\s*at\s+\w+/m.test(msg) ||
    msg.includes('.ts:') ||
    msg.includes('.js:')
  );
}

function stripeHumanMessage(err: Record<string, unknown>): string | null {
  const type = typeof err.type === 'string' ? err.type : '';
  const code = typeof err.code === 'string' ? err.code : '';
  const raw =
    err.raw && typeof err.raw === 'object'
      ? (err.raw as Record<string, unknown>)
      : null;
  const rawCode = raw && typeof raw.code === 'string' ? raw.code : '';

  if (type.includes('Stripe') || code || rawCode) {
    const userMsg = typeof err.message === 'string' ? err.message : '';
    if (userMsg && !isLikelyStackOrInternal(userMsg) && userMsg.length < 300) {
      return userMsg;
    }
    if (rawCode === 'card_declined' || code === 'card_declined') {
      return 'Your card was declined. Please try another card or contact your bank.';
    }
    if (rawCode === 'expired_card' || code === 'expired_card') {
      return 'This card has expired. Please use a different card.';
    }
    if (rawCode === 'incorrect_cvc' || code === 'incorrect_cvc') {
      return 'The security code for your card is incorrect. Please check and try again.';
    }
    if (rawCode === 'processing_error' || code === 'processing_error') {
      return 'We could not process your card. Please try again in a moment.';
    }
    return 'Payment could not be completed. Please try again or use a different payment method.';
  }
  return null;
}

/**
 * @param err - Caught error (or any thrown value)
 * @param fallback - Friendly default when the error should not be shown verbatim
 */
export function humanizeClientError(err: unknown, fallback: string): string {
  if (err == null) {
    return fallback;
  }

  const e = err as Record<string, unknown>;
  if (e.isOperational === true && typeof e.message === 'string' && e.message.trim()) {
    return e.message.trim();
  }

  const name = typeof e.name === 'string' ? e.name : '';
  const msg = typeof e.message === 'string' ? e.message : '';
  const code = e.code as string | number | undefined;

  const stripeMsg = stripeHumanMessage(e);
  if (stripeMsg) {
    return stripeMsg;
  }

  if (name === 'CastError' || msg.includes('Cast to ObjectId failed')) {
    return 'We could not find that item. It may have been removed or the link is no longer valid.';
  }

  if (code === 11000 || msg.toLowerCase().includes('duplicate key')) {
    return 'This information is already in use. Please choose a different value.';
  }

  if (name === 'ValidationError' && e.errors && typeof e.errors === 'object') {
    const joined = joinValidationMessages(
      e.errors as Record<string, { message?: string }>
    );
    if (joined) {
      return joined;
    }
  }

  if (
    name === 'MongoNetworkError' ||
    name === 'MongoServerSelectionError' ||
    name === 'MongoTimeoutError' ||
    msg.includes('ECONNREFUSED') ||
    msg.includes('ETIMEDOUT') ||
    msg.includes('ESOCKETTIMEDOUT')
  ) {
    return 'We are having trouble reaching our database. Please try again in a moment.';
  }

  if (name === 'JsonWebTokenError') {
    return 'Your session is not valid. Please sign in again.';
  }

  if (name === 'TokenExpiredError') {
    return 'Your session has expired. Please sign in again.';
  }

  if (name === 'MulterError') {
    if (code === 'LIMIT_FILE_SIZE') {
      return 'The file is too large. Please upload a smaller file.';
    }
    if (code === 'LIMIT_FILE_COUNT') {
      return 'Too many files were uploaded at once.';
    }
    if (code === 'LIMIT_UNEXPECTED_FILE') {
      return 'The upload included an unexpected file field.';
    }
    return 'Something went wrong with the file upload. Please try again.';
  }

  if (msg.includes('Only image files are allowed')) {
    return 'Only image files are allowed.';
  }
  if (msg.includes('Only image or PDF files are allowed')) {
    return 'Only image or PDF files are allowed.';
  }
  if (msg.includes('Only document files')) {
    return 'Only supported document types are allowed.';
  }

  if (msg.includes('ENOTFOUND') || msg === 'fetch failed') {
    return 'We could not reach an external service. Please try again later.';
  }

  if (msg.includes('data and hash arguments required')) {
    return 'Invalid account information was provided.';
  }

  const lower = msg.toLowerCase();
  if (
    (lower.includes('webhook') && lower.includes('signature')) ||
    lower.includes('no signatures found matching') ||
    lower.includes('stripe-signature')
  ) {
    return 'We could not verify this payment notification. The request may be invalid or outdated.';
  }

  if (!msg.trim() || isLikelyStackOrInternal(msg)) {
    return fallback;
  }

  if (msg.length > 280) {
    return fallback;
  }

  return msg.trim();
}
