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 { PaymentModule } from './payment/payment.module';
import { OrderModule } from './order/order.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，使用 init-db.sql 初始化
        synchronize: false,
        // 连接池配置 - 优化并发性能
        extra: {
          // 连接池最大连接数
          max: configService.get<number>('DB_POOL_SIZE', 20),
          // 连接池最小连接数
          min: 2,
          // 空闲连接超时时间 (ms)
          idleTimeoutMillis: 30000,
          // 连接超时时间 (ms)
          connectionTimeoutMillis: 5000,
        },
        // 日志配置
        logging: configService.get('NODE_ENV') === 'development' ? ['query', 'error'] : ['error'],
        // 重试策略
        retryAttempts: 3,
        retryDelay: 1000,
      }),
    }),

    // Health check
    HealthModule,

    OrderModule,
    PaymentModule,
  ],
})
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('*');
  }
}
