// Package team contains browser-facing Agent Team management routes.
package team

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

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

// Dependencies contains Team route collaborators.
type Dependencies struct {
	AuthStore                 api.SessionAuthenticator
	WorkspaceStore            api.WorkspaceResolver
	Teams                     Store
	EmailVerificationRequired bool
}

func handleTeamWorkspace(handler api.WorkspaceScopedHandler) gin.HandlerFunc {
	return api.HandleWorkspaceScoped(handler)
}

func handleTeamWorkspaceJSON[T any](handler func(api.WorkspaceScopedJSON[T]) (api.Response, error)) gin.HandlerFunc {
	return api.HandleWorkspaceScopedJSON[T](handler)
}

// RegisterRoutes mounts Agent Team management and picker routes.
func RegisterRoutes(router gin.IRouter, dependencies Dependencies) {
	if router == nil {
		return
	}
	apiGroup := router.Group("/api")
	workspaceScoped := apiGroup.Group(
		"/v1/workspaces/:workspaceId",
		api.RequireAuthenticatedUser(dependencies.AuthStore),
		api.RequireVerifiedIdentity(dependencies.EmailVerificationRequired),
		api.RequireRouteWorkspace(dependencies.WorkspaceStore),
	)
	handler := &Handler{store: dependencies.Teams}
	workspaceScoped.GET("/team-templates", handleTeamWorkspace(handler.ListTemplates))
	workspaceScoped.POST("/team-templates", handleTeamWorkspaceJSON[dto.CreateTeamTemplateRequest](handler.CreateTemplate))
	workspaceScoped.PATCH("/team-templates/:templateId", handleTeamWorkspaceJSON[dto.UpdateTeamTemplateRequest](handler.UpdateTemplate))
	workspaceScoped.DELETE("/team-templates/:templateId", handleTeamWorkspace(handler.DeleteTemplate))
	workspaceScoped.POST("/team-templates/:templateId/instantiate", handleTeamWorkspaceJSON[dto.InstantiateTeamTemplateRequest](handler.InstantiateTemplate))
	workspaceScoped.GET("/teams", handleTeamWorkspace(handler.List))
	workspaceScoped.POST("/teams", handleTeamWorkspaceJSON[dto.CreateTeamRequest](handler.Create))
	workspaceScoped.GET("/teams/:teamId", handleTeamWorkspace(handler.Get))
	workspaceScoped.PATCH("/teams/:teamId", handleTeamWorkspaceJSON[dto.UpdateTeamRequest](handler.Update))
	workspaceScoped.DELETE("/teams/:teamId", handleTeamWorkspace(handler.Delete))
	workspaceScoped.POST("/teams/:teamId/template", handleTeamWorkspaceJSON[dto.SaveTeamTemplateFromTeamRequest](handler.SaveTemplateFromTeam))
	workspaceScoped.GET("/teams/:teamId/members", handleTeamWorkspace(handler.ListMembers))
	workspaceScoped.POST("/teams/:teamId/members", handleTeamWorkspaceJSON[dto.AddTeamMemberRequest](handler.AddMember))
	workspaceScoped.PATCH("/teams/:teamId/members/:teamMemberId", handleTeamWorkspaceJSON[dto.UpdateTeamMemberRequest](handler.UpdateMember))
	workspaceScoped.DELETE("/teams/:teamId/members/:teamMemberId", handleTeamWorkspace(handler.RemoveMember))
	workspaceScoped.GET("/mention-candidates/teams", handleTeamWorkspace(handler.MentionCandidates))
}
