import "reflect-metadata";
import { existsSync } from "node:fs";
import { resolve } from "node:path";
import { NestFactory } from "@nestjs/core";
import { FastifyAdapter, NestFastifyApplication } from "@nestjs/platform-fastify";
import cors from "@fastify/cors";
import multipart from "@fastify/multipart";

function loadEnv() {
  const loadEnvFile = process.loadEnvFile as ((path?: string) => void) | undefined;
  if (!loadEnvFile) return;

  for (const envPath of [resolve(process.cwd(), ".env"), resolve(process.cwd(), "../.env"), resolve(process.cwd(), "../../.env")]) {
    if (existsSync(envPath)) {
      loadEnvFile(envPath);
      return;
    }
  }
}

loadEnv();

async function bootstrap() {
  const { AppModule } = await import("./app.module");
  const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
  await app.register(cors, { origin: true });
  await app.register(multipart, { limits: { fileSize: 250 * 1024 * 1024, files: 1 } });
  const fastify = app.getHttpAdapter().getInstance();
  fastify.addContentTypeParser("application/webhook+json", { parseAs: "string" }, (_req, body, done) => {
    done(null, body);
  });
  const port = Number(process.env.PORT ?? 3001);
  await app.listen(port, "0.0.0.0");
  // eslint-disable-next-line no-console
  console.log(`api listening on :${port}`);
}

bootstrap();
