import { BadRequestException, Module, ValidationPipe } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { NotificationsModule } from './shared/notifications/notifications.module';
import { PrismaPostgresModule } from '../prisma/postgres/prisma-postgres.module';
import { ScheduleModule } from '@nestjs/schedule';
import { ConfigModule } from '@nestjs/config';
import { APP_FILTER, APP_PIPE } from '@nestjs/core';
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
import { ValidationError } from 'class-validator';
import { TimeAndAttendanceModule } from 'src/time-and-attendance/time-and-attendance.module';
import { AuthenticationModule } from 'src/identity-and-account/authentication/auth.module';
import { IdentityAndAccountModule } from 'src/identity-and-account/identity-and-account.module';
import { ChatbotModule } from 'src/chatbot/chatbot.module';
import { PrismaMariadbModule } from 'prisma/mariadb/prisma-mariadb.module';
import { PrismaLegacyModule } from 'prisma/prisma-legacy/prisma-legacy.module';
import { AccountModule } from 'src/customer-support/accounts/account.module';

@Module({
  imports: [
    AccountModule,
    AuthenticationModule,
    ConfigModule.forRoot({ isGlobal: true }),
    ScheduleModule.forRoot(), //cronjobs
    NotificationsModule,
    PrismaPostgresModule,
    PrismaMariadbModule,
    PrismaLegacyModule,
    TimeAndAttendanceModule,
    IdentityAndAccountModule,
    ChatbotModule,
  ],
  controllers: [AppController],
  providers: [
    AppService,
    {
      provide: APP_FILTER,
      useClass: HttpExceptionFilter
    },
    {
      provide: APP_PIPE,
      useValue: new ValidationPipe({
        whitelist: true,
        forbidNonWhitelisted: true,
        transform: true,
        exceptionFactory: (errors: ValidationError[] = []) => {
          const messages = errors.flatMap((e) => Object.values(e.constraints ?? {}));
          return new BadRequestException({
            statusCode: 400,
            error: 'Bad Request',
            message: messages.length ? messages : errors,
          });
        },
      }),
    },
  ],
})
export class AppModule { }
