import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

// Patch window.fetch to automatically inject basic auth header for api.canticristiani.it
const originalFetch = window.fetch;
window.fetch = function(input: RequestInfo | URL, init?: RequestInit) {
  const url = typeof input === 'string' ? input : (input instanceof URL ? input.href : input.url);
  if (url.includes('api.canticristiani.it')) {
    init = init || {};
    init.headers = init.headers || {};
    const authHeader = 'Basic ' + btoa(`${environment.apiAuthUser}:${environment.apiAuthPass}`);
    if (init.headers instanceof Headers) {
      init.headers.set('Authorization', authHeader);
    } else if (Array.isArray(init.headers)) {
      const hasAuth = init.headers.some(([key]) => key.toLowerCase() === 'authorization');
      if (!hasAuth) {
        init.headers.push(['Authorization', authHeader]);
      }
    } else {
      (init.headers as Record<string, string>)['Authorization'] = authHeader;
    }
  }
  return originalFetch(input, init);
};

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.log(err));
