
import { toast } from '@/components/ui/use-toast';

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

export function handleError(error: unknown, context?: string) {
  console.error(`Error ${context ? `in ${context}` : ''}:`, error);

  if (error instanceof AppError) {
    toast({
      title: 'Error',
      description: error.message,
      variant: 'destructive',
    });
    return;
  }

  if (error instanceof Error) {
    toast({
      title: 'Unexpected Error',
      description: error.message || 'An unexpected error occurred. Please try again.',
      variant: 'destructive',
    });
    return;
  }

  toast({
    title: 'Error',
    description: 'An unexpected error occurred. Please try again.',
    variant: 'destructive',
  });
}

export async function withErrorHandling<T>(
  fn: () => Promise<T>,
  context?: string
): Promise<T | null> {
  try {
    return await fn();
  } catch (error) {
    handleError(error, context);
    return null;
  }
}
