import { InjectionToken } from '@angular/core';
import type {
  GraphQLAuthHandler,
  GraphQLErrorHandler,
  GraphQLTranslationError,
} from '../graphql.types';
import { auroraGraphqlAuthHandler } from './aurora-graphql-auth.handler';

const defaultErrorHandler: GraphQLErrorHandler = {
  handleGraphQLErrors(errors: readonly GraphQLTranslationError[]): void {
    for (const error of errors) {
      console.error(`[GraphQL Error ${error.statusCode}]: ${error.message}`);
    }
  },
  handleNetworkError(error: Error, statusCode?: number): void {
    console.error(`[Network Error${statusCode != null ? ` ${statusCode}` : ''}]:`, error.message);
  },
};

export const GRAPHQL_ERROR_HANDLER = new InjectionToken<GraphQLErrorHandler>(
  'GraphQLErrorHandler',
  { factory: () => defaultErrorHandler },
);

export const GRAPHQL_AUTH_HANDLER = new InjectionToken<GraphQLAuthHandler>('GraphQLAuthHandler', {
  factory: () => auroraGraphqlAuthHandler,
});
