/*
 * Copyright (C) 2019 Robert Bosch GmbH Copyright (C) 2019 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { ModuleWithProviders, NgModule, Optional, SkipSelf } from '@angular/core';
import { AUTH_OPTIONS } from '../auth-options.token';
import { AuthInterceptor } from '../auth.interceptor';
import { DefaultAuthModuleConfig, IAuthModuleOptions } from '../auth.options';
import { AuthenticationService } from '../services/authentication.service';
import { AuthorizationService } from '../services/authorization.service';
import { AccessControlAuthenticationService } from './services/authentication.service';
import { AccessControlAuthorizationService } from './services/authorization.service';

@NgModule({
  imports: [HttpClientModule],
})
export class AuthModule {
  constructor(@Optional() @SkipSelf() parentModule: AuthModule) {
    if (parentModule) {
      throw new Error("AuthModule is already loaded. It should only be imported in your application's main module.");
    }
  }

  static forRoot(options: IAuthModuleOptions): ModuleWithProviders<AuthModule> {
    return {
      ngModule: AuthModule,
      providers: [
        options.authOptionsProvider || {
          provide: AUTH_OPTIONS,
          useValue: Object.assign({}, DefaultAuthModuleConfig, options.config),
        },
        {
          provide: HTTP_INTERCEPTORS,
          useClass: AuthInterceptor,
          deps: [AUTH_OPTIONS, AuthenticationService],
          multi: true,
        },
        {
          provide: AuthenticationService,
          useClass: AccessControlAuthenticationService,
        },
        {
          provide: AuthorizationService,
          useClass: AccessControlAuthorizationService,
        },
      ],
    };
  }
}
