package router

import (
	"context"

	"github.com/gin-contrib/pprof"
	"github.com/gin-gonic/gin"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
	docs "github.com/tidbcloud/infra-provider/regional-server/api/swagger"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/router/interceptor"
)

type MountFn func(rg *gin.RouterGroup)

const (
	APIV1BasePath = "/api/v1"
)

func route(
	ctx context.Context,
	g *gin.Engine,
	grpcAddr string,
) {
	docs.SwaggerInfo.BasePath = APIV1BasePath
	// support swagger
	swagger := g.Group("/swagger")
	{
		swagger.GET("/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
	}

	// enable pprof
	pprof.Register(g)

	// api
	apiV1 := g.Group(APIV1BasePath)
	apiV1.Use(interceptor.HTTPMetricsMiddleware())
	apiV1.Use(interceptor.ServiceAuthentication)
	{
		apiV1.GET("/", ServiceInfo)
		apiV1.GET("/ping", Ping)
	}
	routeGrpcGateway(ctx, apiV1, grpcAddr)
}

func routeGrpcGateway(ctx context.Context, group *gin.RouterGroup, grpcAddr string) {
	gwMux := setupGRPCGateway(ctx, grpcAddr)
	group.Use(ServeGrpcGatewayPath)
	group.Any("/dataplanes/*any", gin.WrapH(gwMux))
	group.Any("/proxy/dataplanes/*any", gin.WrapH(gwMux))
	group.Any("/nodepoolconfigs/*any", gin.WrapH(gwMux))
	group.Any("/proxy/controlPlane/*any", gin.WrapH(gwMux))
	group.Any("/kongAuditLogSettings", gin.WrapH(gwMux))
	group.Any("/k8sinfos/*any", gin.WrapH(gwMux))
}
