package server

import (
	"context"

	"kra/internal/biz/example"
	"kra/internal/biz/system"
	"kra/internal/conf"
	_ "kra/internal/server/docs"
	examplehandler "kra/internal/server/handler/example"
	handler "kra/internal/server/handler/system"
	"kra/internal/server/middleware"
	"kra/internal/server/router"
	"kra/pkg/jwt"

	"github.com/casbin/casbin/v2"
	"github.com/gin-gonic/gin"
	kgin "github.com/go-kratos/gin"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
	"go.uber.org/zap"
)

// NewGinRouter 创建Gin路由引擎（交给kratos http server管理）
func NewGinRouter(
	c *conf.Server,
	logger *zap.Logger,
	jwtPkg *jwt.JWT,
	enforcer *casbin.SyncedCachedEnforcer,
	jwtBlacklistUsecase *system.JwtBlacklistUsecase,
	userUsecase *system.UserUsecase,
	apiUsecase *system.ApiUsecase,
	authorityUsecase *system.AuthorityUsecase,
	authorityBtnUsecase *system.AuthorityBtnUsecase,
	menuUsecase *system.MenuUsecase,
	dictionaryUsecase *system.DictionaryUsecase,
	casbinUsecase *system.CasbinUsecase,
	operationRecordUsecase *system.OperationRecordUsecase,
	paramsUsecase *system.ParamsUsecase,
	errorUsecase *system.ErrorUsecase,
	versionUsecase *system.VersionUsecase,
	systemUsecase *system.SystemUsecase,
	exportTemplateUsecase *system.ExportTemplateUsecase,
	autoCodeUsecase *system.AutoCodeUsecase,
	autoCodeHistoryUsecase *system.AutoCodeHistoryUsecase,
	autoCodePackageUsecase *system.AutoCodePackageUsecase,
	autoCodeTemplateUsecase *system.AutoCodeTemplateUsecase,
	autoCodePluginUsecase *system.AutoCodePluginUsecase,
	autoCodeMcpUsecase *system.AutoCodeMCPUsecase,
	mcpConfig *conf.MCP,
	// Example usecases
	fileUploadUsecase *example.FileUploadUsecase,
	customerUsecase *example.CustomerUsecase,
	attachmentCategoryUsecase *example.AttachmentCategoryUsecase,
	breakpointContinueUsecase *example.BreakpointContinueUsecase,
) *gin.Engine {
	gin.SetMode(gin.DebugMode)

	engine := gin.New()

	// 使用kratos中间件包装
	engine.Use(kgin.Middlewares(recovery.Recovery()))

	// 设置自定义中间件
	engine.Use(middleware.GinRecovery(true))
	engine.Use(middleware.Cors())

	// 设置日志
	middleware.SetRecoveryLogger(logger)
	middleware.SetOperationLogger(logger)

	// 设置JWT配置
	middleware.SetJWTConfig(&middleware.JWTConfig{
		JWT:              jwtPkg,
		BlacklistChecker: &blacklistChecker{uc: jwtBlacklistUsecase},
		UseMultipoint:    false,
	})

	// 设置Casbin配置
	middleware.SetCasbinConfig(&middleware.CasbinConfig{
		RouterPrefix: "",
	})

	// 初始化system handler依赖
	handler.InitUsecases(
		userUsecase,
		apiUsecase,
		authorityUsecase,
		authorityBtnUsecase,
		menuUsecase,
		dictionaryUsecase,
		casbinUsecase,
		jwtBlacklistUsecase,
		operationRecordUsecase,
		paramsUsecase,
		errorUsecase,
		versionUsecase,
		systemUsecase,
		exportTemplateUsecase,
		autoCodeUsecase,
		autoCodeHistoryUsecase,
		autoCodePackageUsecase,
		autoCodeTemplateUsecase,
		autoCodePluginUsecase,
		autoCodeMcpUsecase,
	)
	handler.SetJWTInstance(jwtPkg)
	handler.InitMcpConfig(mcpConfig, c)

	// 初始化example handler依赖
	examplehandler.InitUsecases(
		fileUploadUsecase,
		customerUsecase,
		attachmentCategoryUsecase,
		breakpointContinueUsecase,
	)

	// 创建路由组
	publicGroup := engine.Group("")
	privateGroup := engine.Group("")
	privateGroup.Use(middleware.JWTAuth()).Use(middleware.CasbinHandler())

	// 注册System路由
	systemRouter := router.RouterGroupApp.System
	systemRouter.InitBaseRouter(publicGroup)
	systemRouter.InitUserRouter(privateGroup)
	systemRouter.InitApiRouter(privateGroup, publicGroup)
	systemRouter.InitAuthorityRouter(privateGroup)
	systemRouter.InitAuthorityBtnRouter(privateGroup)
	systemRouter.InitMenuRouter(privateGroup)
	systemRouter.InitDictionaryRouter(privateGroup)
	systemRouter.InitSysDictionaryDetailRouter(privateGroup)
	systemRouter.InitCasbinRouter(privateGroup)
	systemRouter.InitJwtRouter(privateGroup)
	systemRouter.InitOperationRecordRouter(privateGroup)
	systemRouter.InitParamsRouter(privateGroup)
	systemRouter.InitSysErrorRouter(privateGroup, publicGroup)
	systemRouter.InitSysVersionRouter(privateGroup, publicGroup)
	systemRouter.InitSystemRouter(privateGroup)
	systemRouter.InitSysExportTemplateRouter(privateGroup, publicGroup)
	systemRouter.InitInitRouter(publicGroup)
	systemRouter.InitAutoCodeRouter(privateGroup, publicGroup)
	systemRouter.InitAutoCodeHistoryRouter(privateGroup)

	// 注册Example路由
	exampleRouter := router.RouterGroupApp.Example
	exampleRouter.InitFileUploadRouter(privateGroup)
	exampleRouter.InitCustomerRouter(privateGroup)
	exampleRouter.InitAttachmentCategoryRouter(privateGroup)

	// 注册Swagger文档路由
	engine.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	return engine
}

// blacklistChecker JWT黑名单检查器
type blacklistChecker struct {
	uc *system.JwtBlacklistUsecase
}

func (b *blacklistChecker) IsBlacklist(jwt string) bool {
	return b.uc.IsBlacklist(context.Background(), jwt)
}
