import { Module, OnApplicationBootstrap } from "@nestjs/common";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { TypeOrmModule, TypeOrmModuleOptions } from "@nestjs/typeorm";
import { DataSource, DataSourceOptions } from "typeorm";
import { ensurePostgresSchemas } from "./config/ensure-postgres-schemas";
import { IamModule, DataSeeder } from "@tria-plc/iamapi-common";
import { SharedAuthModule } from "@tria-plc/api-common/modules/auth/shared-auth.module";

import appConfig from "./config/app.config";
import databaseConfig from "./config/database.config";
import telebirrConfig from "./config/telebirr.config";

import { BookingsModule } from "./modules/bookings/bookings.module";
import { FilesModule } from "./modules/files/files.module";
import { ConsignmentsModule } from "./modules/consignments/consignments.module";

// import { TrainsModule } from "./modules/trains/trains.module";
import { LocomotivesModule } from "./modules/locomotives/locomotives.module";
import { WagonTypesModule } from "./modules/wagon-types/wagon-types.module";
import { TrainSetsModule } from "./modules/train-sets/train-sets.module";
import { TrainSchedulesModule } from "./modules/train-schedules/train-schedules.module";
import { TrainSchedulingModule } from "./modules/train-scheduling/train-scheduling.module";
import { CustomersModule } from "./modules/customers/customers.module";
import { CompaniesModule } from "./modules/companies/companies.module";
import { TrackingModule } from "./modules/tracking/tracking.module";
import { BillingModule } from "./modules/billing/billing.module";
import { NotificationsModule } from "./modules/notifications/notifications.module";
import { FileUploadSettingsModule } from "./modules/file-upload-settings/file-upload-settings.module";
import { DropdownSettingsModule } from "./modules/dropdown-settings/dropdown-settings.module";
import { OtpModule } from './modules/otp/otp.module';
import { RuleEngineModule } from "./modules/rule-engine/rule-engine.module";
import { BackofficeModule } from "./modules/backoffice/backoffice.module";
import { DemoPermissionsModule } from "./modules/demo-permissions/demo-permissions.module";
import { FreightAuthModule } from "./modules/auth/freight-auth.module";
import {
  EDR_FREIGHT_APPLICATION,
  EDR_FREIGHT_PERMISSIONS,
} from "./seed/edr-freight.seed";
import { EdrOrgSeeder } from "./seed/edr-org.seeder";
import { DemoUsersSeeder } from "./seed/demo-users.seeder";
import { FreightStaffUsersSeeder } from "./seed/freight-staff-users.seeder";
import { PaymentModule } from "./modules/payment/payment.module";
import { DemoBookingsSeeder } from "./seed/demo-bookings.seeder";
import { PricingDataSeeder } from "./seed/pricing-data.seeder";
import { FileUploadSettingsSeeder } from "./seed/file-upload-settings.seeder";
//New Trains, Wagons, Container and Cargo management modules
import { TrainsModule } from "./modules/trains/trains.module";
import { WagonsModule } from './modules/wagons/wagons.module';
import { ContainersModule } from './modules/container-management/containers.module';
import { CargoesModule } from './modules/cargoes/cargoes.module';
import { RoutesModule } from './modules/routes/routes.module';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      load: [appConfig, databaseConfig, telebirrConfig],
    }),
    // EventEmitterModule.forRoot(),
    TypeOrmModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService): TypeOrmModuleOptions =>
        config.get<TypeOrmModuleOptions>("database")!,
      dataSourceFactory: async (options) => {
        if (!options) {
          throw new Error("Missing TypeORM DataSource options");
        }
        await ensurePostgresSchemas(options as DataSourceOptions);
        const dataSource = new DataSource(options as DataSourceOptions);
        return dataSource.initialize();
      },
    }),
    SharedAuthModule,
    IamModule.forRoot({
      applications: [EDR_FREIGHT_APPLICATION],
      permissions: EDR_FREIGHT_PERMISSIONS,
    }),
    BookingsModule,
    FilesModule,
    ConsignmentsModule,
    LocomotivesModule,
    WagonTypesModule,
    TrainSetsModule,
    TrainSchedulesModule,
    TrainSchedulingModule,
    CustomersModule,
    CompaniesModule,
    TrackingModule,
    BillingModule,
    NotificationsModule,
    FileUploadSettingsModule,
    DropdownSettingsModule,
    OtpModule,
    RuleEngineModule,
    BackofficeModule,
    DemoPermissionsModule,
    FreightAuthModule,
    PaymentModule,
    //New Modules
    TrainsModule,
    WagonsModule,
    ContainersModule,
    CargoesModule,
    RoutesModule,
  ],
  providers: [EdrOrgSeeder, DemoUsersSeeder,FreightStaffUsersSeeder, DemoBookingsSeeder, PricingDataSeeder, FileUploadSettingsSeeder],
})
export class AppModule implements OnApplicationBootstrap {
  constructor(
    private readonly seeder: DataSeeder,
    private readonly edrOrgSeeder: EdrOrgSeeder,
    private readonly demoUsersSeeder: DemoUsersSeeder,
    private readonly freightStaffUsersSeeder: FreightStaffUsersSeeder,
    private readonly demoBookingsSeeder: DemoBookingsSeeder,
    private readonly pricingDataSeeder: PricingDataSeeder,
    private readonly fileUploadSettingsSeeder: FileUploadSettingsSeeder,
  ) { }

  async onApplicationBootstrap() {
    await this.seeder.run();
    await this.edrOrgSeeder.run();
    await this.demoUsersSeeder.run();
    await this.freightStaffUsersSeeder.run();
    await this.demoBookingsSeeder.run();
    await this.pricingDataSeeder.run();
    await this.fileUploadSettingsSeeder.run();
  }
}
