import { Module, NestModule, MiddlewareConsumer, RequestMethod } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { JwtModule } from '@nestjs/jwt';
import {
  TenantContextModule,
  TenantContextMiddleware,
  SimpleTenantFinder,
  DEFAULT_TENANT_ID,
} from '@iconsulting/shared';
import { UserModule } from './user/user.module';
import { AuthModule } from './auth/auth.module';
import { HealthModule } from './health/health.module';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: ['.env.local', '.env'],
    }),

    // Tenant context module (global)
    TenantContextModule.forRoot({
      tenantFinder: SimpleTenantFinder,
      middlewareOptions: {
        allowDefaultTenant: true,
        defaultTenantId: DEFAULT_TENANT_ID,
        excludePaths: ['/health', '/health/*'],
      },
      isGlobal: true,
    }),

    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        type: 'postgres',
        host: configService.get('POSTGRES_HOST', 'localhost'),
        port: configService.get<number>('POSTGRES_PORT', 5432),
        username: configService.get('POSTGRES_USER', 'iconsulting'),
        password: configService.get('POSTGRES_PASSWORD'),
        database: configService.get('POSTGRES_DB', 'iconsulting'),
        entities: [__dirname + '/**/*.orm{.ts,.js}'],
        synchronize: configService.get('NODE_ENV') === 'development',
      }),
    }),

    JwtModule.registerAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        secret: configService.get('JWT_SECRET'),
        signOptions: {
          expiresIn: configService.get('JWT_EXPIRES_IN', '7d'),
        },
      }),
      global: true,
    }),

    // Health check
    HealthModule,

    UserModule,
    AuthModule,
  ],
})
export class AppModule implements NestModule {
  constructor(
    private readonly tenantMiddleware: TenantContextMiddleware,
  ) {}

  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply((req: any, res: any, next: any) => this.tenantMiddleware.use(req, res, next))
      .exclude(
        { path: 'health', method: RequestMethod.GET },
        { path: 'health/(.*)', method: RequestMethod.ALL },
      )
      .forRoutes('*');
  }
}
