package main

import (
	"github.com/golang-jwt/jwt/v4"
	"github.com/kataras/iris/v12/mvc"
	"sparrow/pkg/generator"
	"sparrow/services/knowoapi/controllers"
	"sparrow/services/knowoapi/model"
	"sparrow/services/knowoapi/services"

	jwtmiddleware "github.com/iris-contrib/middleware/jwt"
	"github.com/kataras/iris/v12"
)

func registerErrors(srv *iris.Application) {
	srv.OnAnyErrorCode(handleErrors)
}
func handleErrors(ctx iris.Context) {
	//logger.Default().Serve(ctx)
	err := controllers.ErrorResponse{
		Code:    ctx.GetStatusCode(),
		Message: ctx.Values().GetStringDefault("reason", "未知错误"),
	}
	ctx.JSON(err)
}

// jwt 中间件配置
func newJWThandle() func(ctx iris.Context) {
	jwtHandler := jwtmiddleware.New(jwtmiddleware.Config{
		ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
			return []byte(model.SignedString), nil
		},
		ErrorHandler: func(ctx iris.Context, err error) {
			ctx.StatusCode(iris.StatusUnauthorized)
			ctx.Values().Set("reason", err)
		},
		SigningMethod: jwt.SigningMethodHS256,
	})

	return jwtHandler.Serve
}

// 请求路由
func registerRouters(srv *iris.Application, models *model.All, gen *generator.KeyGenerator) {
	pService := services.NewProductService(models, gen)
	userService := services.NewUserService(models, gen)
	appService := services.NewAppService(models, gen)
	sensorService := services.NewSensorService(models)
	protocalService := services.NewProtocalService(models)
	alertService := services.NewAlertService(models)
	deviceService := services.NewDeviceService(models)
	roleService := services.NewRoleService(models)
	ruleChainService := services.NewRuleChainService(models)
	subDeviceService := services.NewSubDeviceService(models)
	fileService := services.NewFileService()
	otaService := services.NewOtaService(models)
	sceneHisService := services.NewSceneHisService(models)
	deviceCommandService := services.NewDeviceCommandService(models)
	deviceStatusService := services.NewDeviceStatusService(models)
	v1router := srv.Party("/api/v1")

	// 登陆，注册
	loginAPI := mvc.New(v1router.Party("/"))
	loginAPI.Register(userService).Handle(new(controllers.UserController))

	// 用户接口组
	userRouter := v1router.Party("/user", newJWThandle())

	// user api
	userAPI := mvc.New(userRouter.Party("/"))
	userAPI.Register(userService).Handle(new(controllers.UserController))
	// product api
	productAPI := mvc.New(userRouter.Party("/product"))
	productAPI.Register(pService).Handle(new(controllers.ProductController))
	//application api
	appAPI := mvc.New(userRouter.Party("/application"))
	appAPI.Register(appService).Handle(new(controllers.AppController))
	// sensor api
	sensorAPI := mvc.New(userRouter.Party("/sensor"))
	sensorAPI.Register(sensorService).Handle(new(controllers.SensorController))
	// protocal api
	protocalAPI := mvc.New(userRouter.Party("/protocal"))
	protocalAPI.Register(protocalService).Handle(new(controllers.ProtocalController))
	//alert api
	alertAPI := mvc.New(userRouter.Party("/alert"))
	alertAPI.Register(alertService).Handle(new(controllers.AlertController))
	//device api
	deviceAPI := mvc.New(userRouter.Party("/device"))
	deviceAPI.Register(deviceService).Handle(new(controllers.DeviceController))
	//file api
	fileAPI := mvc.New(userRouter.Party("/file"))
	fileAPI.Register(fileService).Handle(new(controllers.FileController))
	//ota api
	otaApi := mvc.New(userRouter.Party("/ota"))
	otaApi.Register(otaService).Handle(new(controllers.OtaController))

	//管理员接口组
	adminRouter := v1router.Party("/admin", newJWThandle())
	RoleAPI := mvc.New(adminRouter.Party("/role"))
	RoleAPI.Register(roleService).Handle(new(controllers.RoleController))

	// ruleChain api
	RuleChainAPI := mvc.New(userRouter.Party("/rule_chain"))
	RuleChainAPI.Register(ruleChainService).Handle(new(controllers.RuleChainController))

	// subDevice api
	subDeviceAPI := mvc.New(userRouter).Party("/sub_device")
	subDeviceAPI.Register(subDeviceService).Handle(new(controllers.SubDeviceController))

	sceneHisAPI := mvc.New(userRouter).Party("/scene_his")
	sceneHisAPI.Register(sceneHisService).Handle(new(controllers.SceneHisController))

	// scene-service 内部调用接口（无需JWT认证）
	sceneHistoryAPI := mvc.New(srv.Party("/iot/v1")).Party("/scene_history")
	sceneHistoryAPI.Register(sceneHisService).Handle(new(controllers.SceneHistoryHandler))

	// deviceCommand api
	deviceCommandAPI := mvc.New(userRouter.Party("/device_command"))
	deviceCommandAPI.Register(deviceCommandService).Handle(new(controllers.DeviceCommandController))

	// deviceStatus api
	deviceStatusAPI := mvc.New(userRouter.Party("/device_status"))
	deviceStatusAPI.Register(deviceStatusService).Handle(new(controllers.DeviceStatusController))
}
