import { Router } from 'express';
import { DataSource } from 'typeorm';
import { ProfilesService, PersonsService } from './services';
import { ProfilesController, PersonsController } from './controllers';
import { Person, UserProfile, ProfileTool, ProfileModule, UserProfileAssignment } from './entities';

export interface ProfilesModuleOptions {
  dataSource: DataSource;
  basePath?: string;
}

export class ProfilesModule {
  public router: Router;
  public profilesService: ProfilesService;
  public personsService: PersonsService;
  private dataSource: DataSource;
  private basePath: string;

  constructor(options: ProfilesModuleOptions) {
    this.dataSource = options.dataSource;
    this.basePath = options.basePath || '';
    this.router = Router();
    this.initializeServices();
    this.initializeRoutes();
  }

  private initializeServices(): void {
    const profileRepository = this.dataSource.getRepository(UserProfile);
    const toolRepository = this.dataSource.getRepository(ProfileTool);
    const moduleRepository = this.dataSource.getRepository(ProfileModule);
    const assignmentRepository = this.dataSource.getRepository(UserProfileAssignment);
    const personRepository = this.dataSource.getRepository(Person);

    this.profilesService = new ProfilesService(
      profileRepository,
      toolRepository,
      moduleRepository,
      assignmentRepository
    );

    this.personsService = new PersonsService(personRepository);
  }

  private initializeRoutes(): void {
    const profilesController = new ProfilesController(this.profilesService);
    const personsController = new PersonsController(this.personsService);

    this.router.use(`${this.basePath}/profiles`, profilesController.router);
    this.router.use(`${this.basePath}/persons`, personsController.router);
  }

  static getEntities(): Function[] {
    return [Person, UserProfile, ProfileTool, ProfileModule, UserProfileAssignment];
  }
}
