/**
 * @copyright 2026 NHCarrigan
 * @license Naomi's Public License
 * @author Naomi Carrigan
 */

import { ErrorHandler, Injectable, inject } from '@angular/core';
import { ToastService } from './toast.service';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  private toast = inject(ToastService);

  handleError(error: Error): void {
    console.error('Global error caught:', error);

    // Show user-friendly error message
    const message = this.getUserFriendlyMessage(error);
    this.toast.error(message);
  }

  private getUserFriendlyMessage(error: Error): string {
    // Check for common error types
    if (error.message.includes('Http failure')) {
      return 'Network error. Please check your connection.';
    }

    if (error.message.includes('401') || error.message.includes('403')) {
      return 'Your session has expired. Please refresh the page.';
    }

    if (error.message.includes('404')) {
      return 'Resource not found.';
    }

    if (error.message.includes('500')) {
      return 'Server error. Please try again later.';
    }

    // Generic error message
    return 'Something went wrong. Please try again.';
  }
}
