import { ApplicationConfig, inject, isDevMode } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
import { provideApollo } from 'apollo-angular';
import { HttpLink } from 'apollo-angular/http';
import { InMemoryCache } from '@apollo/client/core';
import { routes } from './app.routes';
import { environment } from '@env/environment';
import { errorInterceptor } from '@core/interceptors/error.interceptor';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes, withComponentInputBinding()),
    provideHttpClient(withInterceptors([errorInterceptor])),
    provideAnimationsAsync(),
    provideApollo(() => {
      const httpLink = inject(HttpLink);
      return {
        link: httpLink.create({ uri: environment.graphqlUrl }),
        cache: new InMemoryCache({
          typePolicies: {
            Query: {
              fields: {
                students: { merge: (_, incoming) => incoming },
                subjects: { merge: (_, incoming) => incoming },
                availableSubjects: { merge: (_, incoming) => incoming },
                classmates: { merge: (_, incoming) => incoming },
              },
            },
            Student: {
              keyFields: ['id'],
              fields: {
                enrollments: { merge: (_, incoming) => incoming },
              },
            },
            Subject: { keyFields: ['id'] },
            Professor: { keyFields: ['id'] },
            Enrollment: { keyFields: ['id'] },
          },
        }),
        defaultOptions: {
          watchQuery: { fetchPolicy: 'cache-and-network', errorPolicy: 'all' },
          mutate: { errorPolicy: 'all' },
          query: { fetchPolicy: 'cache-first', errorPolicy: 'all' },
        },
        connectToDevTools: isDevMode(),
      };
    }),
  ],
};
