import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { ConfigModule, ConfigService } from '@nestjs/config';
import * as fs from 'fs';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtStrategy } from './strategies/jwt.strategy';
import { TotpService } from './totp.service';
import { EntraIdService } from './sso/entra-id.service';
import { SsoController } from './sso/sso.controller';

@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.registerAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (config: ConfigService) => {
        const privateKeyPath = config.get<string>(
          'JWT_PRIVATE_KEY_PATH',
          '/app/keys/jwt-private.pem',
        );
        const publicKeyPath = config.get<string>(
          'JWT_PUBLIC_KEY_PATH',
          '/app/keys/jwt-public.pem',
        );

        return {
          privateKey: fs.readFileSync(privateKeyPath, 'utf8'),
          publicKey: fs.readFileSync(publicKeyPath, 'utf8'),
          signOptions: {
            algorithm: 'RS256',
            issuer: config.get<string>('JWT_ISSUER', 'insight-platform'),
            expiresIn: config.get<string>('JWT_ACCESS_TOKEN_EXPIRY', '15m'),
          },
          verifyOptions: {
            algorithms: ['RS256'],
            issuer: config.get<string>('JWT_ISSUER', 'insight-platform'),
          },
        };
      },
    }),
  ],
  controllers: [AuthController, SsoController],
  providers: [AuthService, JwtStrategy, TotpService, EntraIdService],
  exports: [AuthService, JwtModule, EntraIdService],
})
export class AuthModule {}
