package vn.io.lcx.vertx.verticle;

@vn.io.lcx.common.annotation.Verticle
@vn.io.lcx.common.annotation.Component
public class ApplicationVerticle extends vn.io.lcx.vertx.base.verticle.VertxBaseVerticle {

    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger("ApplicationVerticle");

${dependencies}

${constructor}

    @Override
    public io.vertx.core.Future<io.vertx.core.http.HttpServer> start() {
        try {
            ${jwt-auth-handler}
            io.vertx.ext.web.Router router = vn.io.lcx.vertx.base.custom.MyRouter.router(super.vertx);
            ${static-resource-handler}
            boolean enableMetric = Boolean.parseBoolean(
                    vn.io.lcx.common.constant.CommonConstant.applicationConfig.getPropertyWithEnvironment("server.enable-metrics") + vn.io.lcx.common.constant.CommonConstant.EMPTY_STRING
            );
            if (enableMetric) {
                router.route("/metrics").handler(io.vertx.micrometer.PrometheusScrapingHandler.create());
            }
            try {
                final Long bodyBytesLimit = (long) vn.io.lcx.common.constant.CommonConstant.applicationConfig.<Integer>getProperty_("server.body-bytes-limit");
                if (bodyBytesLimit == null) {
                    router.route().handler(io.vertx.ext.web.handler.BodyHandler.create());
                } else {
                    router.route().handler(io.vertx.ext.web.handler.BodyHandler.create().setBodyLimit(bodyBytesLimit));
                }
            } catch (Throwable e) {
                logger.info("Create default body handler");
                router.route().handler(io.vertx.ext.web.handler.BodyHandler.create());
            }
            {
                final String cookieAuthName = vn.io.lcx.common.constant.CommonConstant.applicationConfig.getProperty("server.cookie-auth-name");
                if (vn.io.lcx.common.utils.MyStringUtils.isNotBlank(cookieAuthName)) {
                    router.route().handler(ctx -> {
                        if (ctx.request().headers().get("Authorization") == null) {
                            io.vertx.core.http.Cookie cookie = ctx.request().getCookie(cookieAuthName);
                            if (cookie != null && cookie.getValue() != null && !cookie.getValue().isEmpty()) {
                                ctx.request().headers().set("Authorization", "Bearer " + cookie.getValue());
                            }
                        }
                        ctx.next();
                    });
                }
            }

            router.get("/health").handler(routingContext -> routingContext.response().end("OK"));
            router.get("/starting_probe").handler(routingContext -> {
                routingContext.response().end("OK");
            });

            ${router-handler}

            final String portString = vn.io.lcx.common.constant.CommonConstant.applicationConfig.getProperty("server.port");
            int port;
            if (vn.io.lcx.common.utils.MyStringUtils.isNotBlank(portString) && vn.io.lcx.common.utils.MyStringUtils.isNumeric(portString)) {
                port = Integer.parseInt(portString);
            } else {
                port = 8080;
            }
            io.vertx.core.Future<io.vertx.core.http.HttpServer> future;
            io.vertx.core.http.HttpServerOptions serverOptions = vn.io.lcx.common.config.ClassPool.getInstance(io.vertx.core.http.HttpServerOptions.class);
            if (serverOptions != null) {
                future = vertx.createHttpServer(serverOptions)
                        .requestHandler(router)
                        .listen()
                        .onSuccess(server -> {
                            logger.info("Server started on port " + port + " with custom options");
                        });
            } else {
                final boolean enableHttp2 = Boolean.parseBoolean(vn.io.lcx.common.constant.CommonConstant.applicationConfig.getProperty("server.enable-http-2") + vn.io.lcx.common.constant.CommonConstant.EMPTY_STRING);
                if (enableHttp2) {
                    future = vertx.createHttpServer(vn.io.lcx.vertx.base.config.HttpOption.configureHttp2H2C(port))
                            .requestHandler(router)
                            .listen()
                            .onSuccess(server -> {
                                logger.info("HTTP2 server started on port " + port);
                            });
                } else {
                    future = vertx.createHttpServer()
                            .requestHandler(router)
                            .listen(port)
                            .onSuccess(server -> {
                                logger.info("HTTP server started on port " + port);
                            });
                }
            }
            return future;
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
    }
${auth-method}
}
