import { ApiError } from "./client"

/**
 * Extract a user-facing error message from a thrown ApiError (or any unknown error).
 * Order: first Laravel field error → payload.message → error.message → fallback.
 */
export function parseApiError(error: unknown, fallback = "Request failed"): string {
    const e = error as { payload?: { errors?: unknown; message?: string }; message?: string } | undefined
    if (!e) return fallback

    const errors = e.payload?.errors
    if (errors && typeof errors === "object" && !Array.isArray(errors)) {
        const first = Object.values(errors as Record<string, unknown>)[0]
        if (Array.isArray(first) && typeof first[0] === "string") {
            return first[0]
        }
        if (typeof first === "string") {
            return first
        }
    }

    if (typeof e.payload?.message === "string" && e.payload.message.length > 0) {
        return e.payload.message
    }

    if (error instanceof ApiError && error.message) {
        return error.message
    }

    if (typeof e.message === "string" && e.message.length > 0) {
        return e.message
    }

    return fallback
}
