import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import {
  FastifyAdapter,
  NestFastifyApplication
} from '@nestjs/platform-fastify';
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
import fastifyCookie from '@fastify/cookie';
import * as path from 'path';
import * as fs from 'fs';
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
  const isProd = process.env.NODE_ENV === 'prod';
  let httpsOptions = {};
  if (!isProd) {
    const certPath = path.join(__dirname, "..\\..", "certs");
    httpsOptions = {
      key: fs.readFileSync(path.join(certPath, 'localhost+2-key.pem')),
      cert: fs.readFileSync(path.join(certPath, 'localhost+2.pem'))
    };
  }
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(!isProd ? { https: httpsOptions } : undefined)
  );
  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      whitelist: true,
      forbidNonWhitelisted: true,
      transformOptions: {
        enableImplicitConversion: true
      }
    })
  )
  app.enableCors({
    origin: (origin, callback) => {
      // origin이 없는 경우(local file, curl 등) 허용
      if (!origin) return callback(null, true);

      // 특정 도메인만 막고 싶은 경우 whitelist 가능
      const whitelist = ["http://localhost:5173", "http://192.168.219.105:5185", "https://scheduler.bkdhome.p-e.kr"];
      if (whitelist.includes(origin)) {
        return callback(null, true);
      }

      // 그 외 모든 도메인 허용 → 사실상 wildcard
      return callback(null, true);
    },
    credentials: true,
  });

  app.enableShutdownHooks();
  app.useGlobalFilters(new AllExceptionsFilter());
  app.register(fastifyCookie, {
    secret: process.env.JWT_SECRET
  });
  await app.listen(process.env.PORT ?? 3000, '0.0.0.0', () => { process.env.NODE_ENV !== 'prod' && console.log(`servier is running on ${process.env.PORT}`) });
  // await app.listen(process.env.PORT || 3000, () => { process.env.NODE_ENV !== 'prod' && console.log(`service is running on ${process.env.PORT}`)});
}
bootstrap();
