/**
 * Error display utilities
 * Converts errors to user-friendly messages
 */

import { isApiError } from "@/lib/api/runtime/client";

export function toUserMessage(error: unknown): string {
  if (typeof error === "string") {
    return error;
  }

  // Handle API errors with specific status codes
  if (isApiError(error)) {
    const status = error.response?.status;
    const body = error.body as Record<string, unknown> | undefined;

    // Rate limit error (429)
    if (status === 429) {
      return "Too many requests. Please wait a moment and try again.";
    }

    // Get message from error body
    if (body && typeof body.error === "object") {
      const errorObj = body.error as Record<string, unknown>;
      if (typeof errorObj.message === "string") {
        return errorObj.message;
      }
    }

    if (body && typeof body.message === "string") {
      return body.message;
    }
  }

  if (error && typeof error === "object" && "message" in error) {
    return String(error.message);
  }

  return "An unexpected error occurred";
}
