/**
 * Error Handler Service
 */

import { toast } from 'sonner';

export class AppError extends Error {
  constructor(
    message: string,
    public code?: string,
    public statusCode?: number
  ) {
    super(message);
    this.name = 'AppError';
  }
}

export const handleApiError = (error: any): string => {
  if (error.response?.data?.detail) {
    return error.response.data.detail;
  }
  if (error.message) {
    return error.message;
  }
  return 'An unexpected error occurred';
};

/**
 * Global error handler for the application
 */
export const handleError = (
  error: unknown,
  context?: string,
  options?: {
    customMessage?: string;
    showToast?: boolean;
  }
): void => {
  const message = options?.customMessage || 'An error occurred';
  console.error(`[Error${context ? ` (${context})` : ''}]:`, error);

  if (options?.showToast !== false) {
    toast.error(message);
  }
};

/**
 * Show success message
 */
export const showSuccess = (
  title: string,
  description?: string
): void => {
  toast.success(title, {
    description,
  });
};
