import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import * as path from 'path';
import * as express from 'express';

async function bootstrap() {
const app = await NestFactory.create(AppModule, { rawBody: true });
const appConfig = app.get(ConfigService);
const port = appConfig.get<number>('app.port')!;
const apiPrefix = appConfig.get('app.apiPrefix');


// Serve Next.js static app from root (only for non-API routes) (public/app)
const frontendPath = path.join(process.cwd(), 'public', 'app');
app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
// Skip if it's an API route, public route, or Swagger docs
if (req.path.startsWith(`/${apiPrefix}`) || req.path.startsWith('/public')) {
return next();
}
// Try to serve static file first
express.static(frontendPath)(req, res, (err) => {
if (err) {
return next(err);
}
// If no static file found, serve index.html for SPA routing
const indexPath = path.join(frontendPath, 'index.html');
if (require('fs').existsSync(indexPath)) {
res.sendFile(indexPath);
} else {
res.status(404).send('Frontend app not found. Please build and deploy the Next.js app first.');
}
});
});


await app.listen(port);
console.log(`Application running on: http://localhost:${port}`);
console.log(`Swagger UI: http://localhost:${port}/api/docs`);
}
bootstrap();