package dispatch

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/dig"

	"github.com/tidbcloud/aisupport/packages/sdk-go/infra/apiserver"
	"github.com/tidbcloud/aisupport/services/ticket-manager/config"
	"github.com/tidbcloud/aisupport/services/ticket-manager/internal/app"
	coreint "github.com/tidbcloud/aisupport/services/ticket-manager/internal/integrations/core"
	"github.com/tidbcloud/aisupport/services/ticket-manager/internal/integrations/oncall"
	dispatchsvcapi "github.com/tidbcloud/aisupport/services/ticket-manager/internal/services/dispatch/api"
)

type HandlerParam struct {
	dig.In

	Dispatch dispatchsvcapi.Service
	Core     *coreint.Client
	Oncall   oncall.Client
	Config   *config.RootConfig
}

type Handler struct {
	Dispatch dispatchsvcapi.Service
	Core     *coreint.Client
	Oncall   oncall.Client
	Config   config.DispatchServiceConfig
}

func NewHandler(param HandlerParam) app.HandlerResult {
	return app.HandlerResult{Handler: &Handler{Dispatch: param.Dispatch, Core: param.Core, Oncall: param.Oncall, Config: param.Config.Services.Dispatch}}
}

func (h *Handler) Name() string {
	return "DispatchHandler"
}

func (h *Handler) Register(routers map[apiserver.RoutePath]gin.IRouter) error {
	router := routers[app.APIRoutePath]
	g := router.Group("/dispatch")
	g.GET("/options", h.GetOptions)

	g.GET("/contexts/:issue_key", h.GetDispatchContext)
	g.GET("/projects/:project_key/components", h.ListProjectComponents)

	g.POST("/triggers", h.CreateDispatchTrigger)
	g.GET("/triggers", h.ListDispatchTriggers)
	g.GET("/triggers/:id", h.GetDispatchTrigger)
	g.GET("/executions", h.ListExecutions)
	g.GET("/executions/:id", h.GetExecution)
	g.GET("/insights", h.GetInsight)

	g.GET("/policies", h.ListPolicies)
	g.POST("/policies", h.CreatePolicy)
	g.GET("/policies/:id", h.GetPolicy)
	g.PUT("/policies/:id", h.UpdatePolicy)
	g.DELETE("/policies/:id", h.DeletePolicy)
	g.POST("/policies/:id/publish", h.PublishPolicy)
	g.POST("/policies/:id/retire", h.RetirePolicy)
	return nil
}
