package invocation

import (
	"github.com/gin-gonic/gin"

	"github.com/tidbcloud/AgentTeam/internal/api"
	"github.com/tidbcloud/AgentTeam/internal/api/dto"
)

type Dependencies struct {
	AuthStore                 api.SessionAuthenticator
	WorkspaceStore            api.WorkspaceResolver
	EmailVerificationRequired bool
	Service                   Service
}

func handleWorkspace(handler api.WorkspaceScopedHandler) gin.HandlerFunc {
	return api.HandleWorkspaceScoped(handler, api.WithErrorClassifier(classifyError))
}

func handleCreate(handler func(api.WorkspaceScopedJSON[dto.WorkflowInvocationCreateRequest]) (api.Response, error)) gin.HandlerFunc {
	return api.HandleWorkspaceScoped(func(request api.WorkspaceScopedRequest) (api.Response, error) {
		body, err := decodeWorkflowInvocationCreateJSON(request.Gin)
		if err != nil {
			return api.Response{}, err
		}
		return handler(api.WorkspaceScopedJSON[dto.WorkflowInvocationCreateRequest]{
			WorkspaceScopedRequest: request,
			Body:                   body,
		})
	}, api.WithErrorClassifier(classifyError))
}

// RegisterRoutes mounts the human direct-Plan Invocation surface plus immutable
// workspace collection/detail reads.
func RegisterRoutes(router gin.IRouter, dependencies Dependencies) {
	if router == nil || dependencies.Service == nil {
		return
	}
	workspaceScoped := router.Group(
		"/api/v1/workspaces/:workspaceId",
		api.RequireAuthenticatedUser(dependencies.AuthStore),
		api.RequireVerifiedIdentity(dependencies.EmailVerificationRequired),
		api.RequireRouteWorkspace(dependencies.WorkspaceStore),
	)
	handler := NewHandler(dependencies.Service)
	workspaceScoped.POST("/workflow/plans/:planId/invocations", handleCreate(handler.InvokeManual))
	workspaceScoped.GET("/workflow/invocations", handleWorkspace(handler.List))
	workspaceScoped.GET("/workflow/invocations/:invocationId", handleWorkspace(handler.Get))
}
