import { INestApplication } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { ConfigService } from '@nestjs/config';

export function setupSwagger(app: INestApplication, config: ConfigService) {
  const enabled = config.get<boolean>('swagger.enabled');
  if (!enabled) return;

  const path = config.get<string>('swagger.path') ?? 'docs';

  const docConfig = new DocumentBuilder()
    .setTitle(config.get<string>('app.name') ?? 'cashi-backend')
    .setDescription('API documentation')
    .setVersion('1.0.0')
    .addBearerAuth(
      {
        type: 'http',
        scheme: 'bearer',
        bearerFormat: 'JWT',
        in: 'header',
      },
      'bearer',
    )
    .build();

  const document = SwaggerModule.createDocument(app, docConfig, {
    // We serve APIs under `/api/*` via `setGlobalPrefix('api')`
    ignoreGlobalPrefix: false,
  });
  SwaggerModule.setup(path, app, document, {
    // Avoid relying on serving swagger-ui-dist static files from serverless bundles.
    customCssUrl: 'https://unpkg.com/swagger-ui-dist@5/swagger-ui.css',
    customJs: [
      'https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js',
      'https://unpkg.com/swagger-ui-dist@5/swagger-ui-standalone-preset.js',
    ],
    swaggerOptions: {
      persistAuthorization: true,
    },
  });
}
