import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { ThrottlerModule } from '@nestjs/throttler';
import { BullModule } from '@nestjs/bullmq';
import { TypeOrmModule } from '@nestjs/typeorm';
import { TrackingModule } from './tracking/tracking.module';
import { HealthModule } from './health/health.module';
import { RawEvent } from './entities/raw-event.entity';
import { SessionFingerprint } from "./entities/session-fingerprint.entity";
import { Corp } from "./entities/corp.entity";
import { Domain } from "./entities/domain.entity";
import { VisitorSalt } from "./entities/visitor-salt.entity";
import { WriteKeyGuard } from './auth/write-key.guard';

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

    // Rate limiting
    ThrottlerModule.forRoot([
      {
        ttl: 60000, // 1 minute
        limit: 1000, // 1000 requests per minute
      },
    ]),

    // Database
    TypeOrmModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        type: 'postgres',
        host: config.get('DATABASE_HOST', 'localhost'),
        port: config.get('DATABASE_PORT', 5432),
        username: config.get('DATABASE_USER', 'analytics'),
        password: config.get('DATABASE_PASSWORD', 'analytics'),
        database: config.get('DATABASE_NAME', 'analytics'),
        entities: [RawEvent, SessionFingerprint, Corp, Domain, VisitorSalt],
        synchronize: config.get('DB_SYNCHRONIZE') === 'true',
        logging: config.get('NODE_ENV') === 'development',
      }),
    }),

    // Queue for async processing
    BullModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService) => {
        const password = config.get<string>('REDIS_PASSWORD');
        return {
          connection: {
            host: config.get('REDIS_HOST', 'localhost'),
            port: config.get('REDIS_PORT', 6379),
            ...(password ? { password } : {}),
          },
        };
      },
    }),

    BullModule.registerQueue({
      name: 'analytics-events',
    }),

    // Feature modules
    TrackingModule,
    HealthModule,
  ],
  providers: [
    {
      provide: APP_GUARD,
      useClass: WriteKeyGuard,
    },
  ],
})
export class AppModule {}
