import './otel';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import {
  FastifyAdapter,
  NestFastifyApplication,
} from '@nestjs/platform-fastify';
import FastifyMulter from 'fastify-multer';
import fastifyStatic from '@fastify/static';
import * as path from 'path';
import * as fs from 'fs';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter({
      logger: true,
    }),
  );

  app.enableCors({
    origin: '*',
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
    allowedHeaders: ['Content-Type', 'Authorization'],
    credentials: true,
  });

  const fastifyApp = app.getHttpAdapter().getInstance();
  await fastifyApp.register(FastifyMulter().contentParser);
  // @fastify/static exige un chemin absolu existant : UPLOAD_PATH peut être
  // relatif (cf. apps/api/.env.test) et le dossier peut ne pas encore exister.
  const staticRoot = path.resolve(
    process.env.UPLOAD_PATH || __dirname,
    'shootings',
  );
  fs.mkdirSync(staticRoot, { recursive: true });
  await fastifyApp.register(fastifyStatic, {
    root: staticRoot,
  });

  await app.listen(process.env.PORT ?? 3001, '0.0.0.0');
}
bootstrap();
