import { HttpErrorResponse } from '@angular/common/http';

const GENERIC_API_TITLES = new Set([
  'An unexpected error occurred.',
  'Internal Server Error',
]);

export function extractApiError(error: unknown, fallback = 'Something went wrong.'): string {
  if (error instanceof HttpErrorResponse) {
    const data = error.error as { error?: string; title?: string } | undefined;
    if (data?.error) return data.error;
    if (data?.title && !GENERIC_API_TITLES.has(data.title)) return data.title;
    return fallback;
  }
  if (error instanceof Error) {
    return error.message;
  }
  return fallback;
}
