/**
 * Error utility functions
 */

import { ZodError } from 'zod'

/**
 * Convert unknown error to string message
 * Handles Error objects and other types safely
 * Includes special handling for Zod validation errors
 */
export function errorToString(error: unknown): string {
  if (error instanceof ZodError) {
    // Format Zod validation errors with field path and details
    return JSON.stringify(error.issues, null, 2)
  }
  return error instanceof Error ? error.message : String(error)
}

/**
 * Extract structured error details for logging
 * Includes validation errors, stack traces, and context
 */
export function getErrorDetails(error: unknown): Record<string, unknown> {
  const details: Record<string, unknown> = {
    message: errorToString(error),
    type: error instanceof Error ? error.constructor.name : typeof error
  }

  // Add Zod validation details
  if (error instanceof ZodError) {
    details.validationErrors = error.issues
    details.isValidationError = true
  }

  // Add stack trace for Error objects
  if (error instanceof Error && error.stack) {
    details.stack = error.stack
  }

  return details
}