import { parseDomainError } from "../response-helpers";

/**
 * Extract a user-facing error message from an API error payload.
 *
 * Supports:
 * - domain envelope: `{ success: false, error: { code, message, details? } }`
 * - common nested error: `{ error: { message } }`
 * - top-level message: `{ message }`
 */
export function getApiErrorMessage(payload: unknown): string | null {
  const domainError = parseDomainError(payload);
  if (domainError) {
    return domainError.error.message;
  }

  if (!payload || typeof payload !== "object") {
    return null;
  }

  const bodyWithError = payload as { error?: { message?: unknown } };
  if (bodyWithError.error && typeof bodyWithError.error === "object") {
    const errorMessage = bodyWithError.error.message;
    if (typeof errorMessage === "string") {
      return errorMessage;
    }
  }

  const bodyWithMessage = payload as { message?: unknown };
  if (typeof bodyWithMessage.message === "string") {
    return bodyWithMessage.message;
  }

  return null;
}
