import { ExceptionCode } from "../exception-code";
import type { ExceptionResult } from "../exception-result";

export const DEFAULT_EXCEPTION_MESSAGE =
  "Something went wrong. Please try again.";

export class FallbackExceptionHandler {
  static handle(error: unknown): ExceptionResult {
    return {
      code: ExceptionCode.unknown,
      message: resolveMessage(error),
    };
  }
}

function resolveMessage(error: unknown): string {
  if (error instanceof Error && error.message.trim().length > 0) {
    return error.message;
  }

  if (typeof error === "string" && error.trim().length > 0) {
    return error;
  }

  if (isMessageLike(error) && error.message.trim().length > 0) {
    return error.message;
  }

  return DEFAULT_EXCEPTION_MESSAGE;
}

function isMessageLike(error: unknown): error is { message: string } {
  return (
    typeof error === "object" &&
    error !== null &&
    "message" in error &&
    typeof error.message === "string"
  );
}
