import { ValidationPipe } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  const configService = app.get(ConfigService);

  app.enableCors({
    origin: true,
    credentials: true,
  });
  app.setGlobalPrefix('api');
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      transform: true,
    }),
  );

  const swaggerConfig = new DocumentBuilder()
    .setTitle('城市照明综合网管平台 API')
    .setDescription('权限、区域、路灯、报警和地图接口')
    .setVersion('1.0.0')
    .addBearerAuth()
    .build();
  const document = SwaggerModule.createDocument(app, swaggerConfig);
  SwaggerModule.setup('api/docs', app, document);

  const frontendDistPath = resolveFrontendDistPath();
  if (frontendDistPath) {
    app.useStaticAssets(frontendDistPath);
    const indexPath = join(frontendDistPath, 'index.html');
    app.use((req: any, res: any, next: () => void) => {
      if (req.method !== 'GET' || req.path.startsWith('/api') || /\.[^/]+$/.test(req.path)) {
        next();
        return;
      }
      res.sendFile(indexPath);
    });
  }

  await app.listen(Number(configService.get('PORT') ?? 3000));
}

function resolveFrontendDistPath() {
  const candidates = [
    join(process.cwd(), 'front', 'dist'),
    join(process.cwd(), '..', 'front', 'dist'),
    join(__dirname, '..', '..', 'front', 'dist'),
    join(__dirname, '..', '..', '..', 'front', 'dist'),
  ];

  return candidates.find((path) => existsSync(join(path, 'index.html')));
}

void bootstrap();
