import { Module, NestModule, MiddlewareConsumer, RequestMethod } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import {
  TenantContextModule,
  TenantContextMiddleware,
  SimpleTenantFinder,
  DEFAULT_TENANT_ID,
} from '@iconsulting/shared';
import { HealthModule } from './health/health.module';
import { FileModule } from './file/file.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: (config: ConfigService) => ({
        type: 'postgres',
        host: config.get('POSTGRES_HOST', 'localhost'),
        port: config.get<number>('POSTGRES_PORT', 5432),
        username: config.get('POSTGRES_USER', 'postgres'),
        password: config.get('POSTGRES_PASSWORD'),
        database: config.get('POSTGRES_DB', 'iconsulting'),
        autoLoadEntities: true,
        synchronize: config.get('NODE_ENV') !== 'production',
        logging: config.get('NODE_ENV') === 'development',
      }),
    }),

    // Health check
    HealthModule,

    // 功能模块
    FileModule,
  ],
})
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('*');
  }
}
