import {
  ClassSerializerInterceptor,
  UseGuards,
  ValidationPipe,
  VersioningType,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory, Reflector } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { useContainer } from 'class-validator';
import { CrudConfigService } from '@dataui/crud';
import { Roles } from './auth/decorators/roles.decorator';
import { RoleEnum } from './users/enums/role.enum';
import { RoleGuard } from './auth/guards/role.guard';
import { AuthGuard } from '@nestjs/passport';


CrudConfigService.load({
  routes: {
    createOneBase: {
      decorators: [Roles(RoleEnum.SUPER_ADMIN, RoleEnum.ADMIN), UseGuards(AuthGuard('jwt'), RoleGuard)],
    },
    replaceOneBase: {
      decorators: [Roles(RoleEnum.SUPER_ADMIN, RoleEnum.ADMIN), UseGuards(AuthGuard('jwt'), RoleGuard)],
    },
    deleteOneBase: {
      decorators: [Roles(RoleEnum.SUPER_ADMIN, RoleEnum.ADMIN), UseGuards(AuthGuard('jwt'), RoleGuard)],
    },
    updateOneBase: {
      decorators: [Roles(RoleEnum.SUPER_ADMIN, RoleEnum.ADMIN), UseGuards(AuthGuard('jwt'), RoleGuard)],
    },
    createManyBase: {
      decorators: [Roles(RoleEnum.SUPER_ADMIN, RoleEnum.ADMIN), UseGuards(AuthGuard('jwt'), RoleGuard)],
    },
  },
});

import { AppModule } from './app.module';
import validationOptions from './utils/validation-options';
import { AllConfigType } from './config/config.type';
import express from 'express';
import { join } from 'path';


async function bootstrap() {
  const app = await NestFactory.create(AppModule, { cors: true });
  useContainer(app.select(AppModule), { fallbackOnErrors: true });
  const configService = app.get(ConfigService<AllConfigType>);

  app.use('/public', express.static(join(__dirname, '..', 'public'))); // <-

  app.enableShutdownHooks();
  app.setGlobalPrefix(
    configService.getOrThrow('app.apiPrefix', { infer: true }),
    {
      exclude: ['/'],
    },
  );
  app.enableVersioning({
    type: VersioningType.URI,
  });
  app.useGlobalPipes(new ValidationPipe(validationOptions));
  app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));

  const options = new DocumentBuilder()
    .setTitle('API')
    .setDescription('API docs')
    .setVersion('1.0')
    .addBearerAuth()
    .build();

  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('docs', app, document);

  await app.listen(configService.getOrThrow('app.port', { infer: true }));
}
void bootstrap();
