package routes

import (
	"dashboard/controller"
	"dashboard/logger"
	"dashboard/pkg/jwt"
	"dashboard/settings"
	"time"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

func Setup(log *logger.Logger, rate settings.RateLimitConfig, jwtC settings.JwtConfig) *gin.Engine {
	cjwt := jwt.New(jwt.WithSalt(jwtC.Salt), jwt.WithExpire(time.Duration(jwtC.Expire)*time.Second))

	r := gin.New()

	r.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "POST"},
		AllowHeaders:     []string{"Origin", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
		MaxAge:           12 * time.Hour,
	}))

	r.Use(GinLogger(log), GinRecovery(log, true), GinLog(log), errWapper(GinRateLimit(rate)))

	// 静态文件服务
	r.Static("/static", "./static")
	r.StaticFile("/", "./static/index.html")

	r.GET("login", controller.LoginPage)

	r.POST("/api/login", errWapper(controller.UserSignInHandler(cjwt)))
	r.POST("/api/logout", controller.UserLogOutHandler)

	g1 := r.Group("/api")
	g1.Use(errWapper(GinJwtAuthor(cjwt)))
	{
		g1.GET("/system-info", errWapper(controller.SystemInfoHandle))
		g1.POST("/upload", errWapper(controller.FileUploadHandle))
		g1.GET("/files", errWapper(controller.FileListHandle))
		g1.GET("/download", errWapper(controller.FileDownloadHandle))
	}

	r.GET("/ws/terminal", errWapper(GinJwtAuthor(cjwt)), errWapper(controller.TerminalHandle()))

	return r
}
