import swaggerJsDoc, { OAS3Options, Options, SecurityRequirement } from 'swagger-jsdoc';
import { Middleware } from '../base/http';
import swaggerUi from 'swagger-ui-express';
import { $$ } from '../base/i18n';
import { MiddlewareOrder } from './MiddlewareOrder';

class SwaggerUiSetupMiddleware extends Middleware {
	protected order = MiddlewareOrder.SwaggerUiSetupMiddleware;
	protected route = this.context.swaggerRoute;
	protected action: any = this.getSetup();

	private getSetup(): any {
		if(!this.context.swaggerDocsPath)
			return (req: Request, res: Response, next: any) => { next(); };

		const swaggerOptions : OAS3Options = {
			swaggerDefinition: {
				openapi: '3.0.1',
				info: {
					title: this.context.swaggerTitle!,
					version: this.context.swaggerApiVersion!,
					description: this.context.swaggerDescription!,
				},
				servers: [
					{ url: this.context.host }
				],
			},
			apis: [this.context.swaggerDocsPath],
		};

		if(this.context.swaggerComponents)
			swaggerOptions.swaggerDefinition!.components = this.context.swaggerComponents;
		if(this.context.swaggerSecurity)
			swaggerOptions.swaggerDefinition!.security = this.context.swaggerSecurity as SecurityRequirement[];

		const swaggerDocs = swaggerJsDoc(swaggerOptions as Options);

		this.context.logInfo($$('org.crazydoctor.expressts.swagger.registered', { path: this.context.swaggerRoute }));

		return swaggerUi.setup(swaggerDocs);

	}
}

export { SwaggerUiSetupMiddleware };