import { MiddlewareConsumer, Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { PassportModule } from '@nestjs/passport';
import * as dotenv from 'dotenv';
import fs from 'fs-extra';
import { WinstonModule, utilities as nestWinstonModuleUtilities } from 'nest-winston';
import * as winston from 'winston';
import { AiModule } from './ai/ai.module.js';
import { AppController } from './app.controller.js';
import { AppService } from './app.service.js';
import { AuthModule } from './auth/auth.module.js';
import { FileService } from './file/file.service.js';
import { GeoModule } from './geo/geo.module.js';
import { ImageModule } from './image/image.module.js';
import { ListingsModule } from './listings/listings.module.js';
import { MailModule } from './mail/mail.module.js';
import { RequestDurationMiddleware } from './request-duration/request-duration.middleware.js';
import { SelectOptionsModule } from './select-options/select-options.module.js';
import { UserModule } from './user/user.module.js';
// const __filename = fileURLToPath(import.meta.url);
// const __dirname = path.dirname(__filename);

function loadEnvFiles() {
  // Load the .env file
  dotenv.config();
  console.log('Loaded .env file');

  // Determine which additional env file to load
  let envFilePath = '';
  const host = process.env.HOST_NAME || '';

  if (host.includes('localhost')) {
    envFilePath = '.env.local';
  } else if (host.includes('dev.bizmatch.net')) {
    envFilePath = '.env.dev';
  } else if (host.includes('www.bizmatch.net') || host.includes('bizmatch.net')) {
    envFilePath = '.env.prod';
  }

  // Load the additional env file if it exists
  if (fs.existsSync(envFilePath)) {
    dotenv.config({ path: envFilePath });
    console.log(`Loaded ${envFilePath} file`);
  } else {
    console.log(`No additional .env file found for HOST_NAME: ${host}`);
  }
}

loadEnvFiles();
@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    MailModule,
    AuthModule,
    WinstonModule.forRoot({
      transports: [
        new winston.transports.Console({
          format: winston.format.combine(
            winston.format.timestamp(),
            winston.format.ms(),
            nestWinstonModuleUtilities.format.nestLike('Bizmatch', {
              colors: true,
              prettyPrint: true,
            }),
          ),
        }),
        // other transports...
      ],
      // other options
    }),
    GeoModule,
    UserModule,
    ListingsModule,
    SelectOptionsModule,
    ImageModule,
    PassportModule,
    AiModule,
  ],
  controllers: [AppController],
  providers: [AppService, FileService],
})
export class AppModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(RequestDurationMiddleware).forRoutes('*');
  }
}
