package rest

import (
	"database/sql"

	"github.com/gin-gonic/gin"
	"github.com/nexuscrm/backend/internal/features/automation"
	"github.com/nexuscrm/backend/internal/features/metadata"
)

// FlowHandler handles Salesforce-compatible Flow API endpoints.
// Method implementations are split across domain-specific files:
//   - flow_invocable.go  — ListInvocableFlows, GetFlowSchema, ExecuteFlow
//   - flow_interviews.go — ListInterviews, GetInterview, DeleteInterview, ResumeInterview
//   - flow_tooling.go    — FlowDefinition CRUD, FlowVersion CRUD
type FlowHandler struct {
	executor   *automation.FlowExecutor
	interviews *automation.FlowInterviewService
	metadata   *metadata.MetadataService
	db         *sql.DB
}

// NewFlowHandler creates a new FlowHandler
func NewFlowHandler(
	executor *automation.FlowExecutor,
	interviews *automation.FlowInterviewService,
	metadata *metadata.MetadataService,
	db ...*sql.DB,
) *FlowHandler {
	var standardActionDB *sql.DB
	if len(db) > 0 {
		standardActionDB = db[0]
	}
	return &FlowHandler{
		executor:   executor,
		interviews: interviews,
		metadata:   metadata,
		db:         standardActionDB,
	}
}

// Route Registration

// RegisterRoutes registers all flow-related routes
// Note: Caller should pass the /actions/custom group, not /services/data/:version
func (h *FlowHandler) RegisterRoutes(router *gin.RouterGroup) {
	router.GET("/flow", h.ListInvocableFlows)
	router.GET("/flow/:name", h.GetFlowSchema)
	router.POST("/flow/:name", h.ExecuteFlow)
	router.POST("/resumeFlow", h.ResumeInterview)
}

// RegisterSObjectRoutes registers FlowInterview sobject routes
// Call this with the /sobjects group
func (h *FlowHandler) RegisterSObjectRoutes(router *gin.RouterGroup) {
	router.GET("/FlowInterview", h.ListInterviews)
	router.GET("/FlowInterview/:id", h.GetInterview)
	router.DELETE("/FlowInterview/:id", h.DeleteInterview)
}

// RegisterToolingRoutes registers Tooling API routes for Flow management
// Call this with the /tooling/sobjects group
func (h *FlowHandler) RegisterToolingRoutes(router *gin.RouterGroup) {
	// FlowDefinition CRUD
	router.GET("/FlowDefinition", h.ListFlowDefinitions)
	router.GET("/FlowDefinition/:id", h.GetFlowDefinition)
	router.POST("/FlowDefinition", h.CreateFlowDefinition)
	router.PATCH("/FlowDefinition/:id", h.UpdateFlowDefinition)
	router.DELETE("/FlowDefinition/:id", h.DeleteFlowDefinition)

	// Flow (version) CRUD
	router.GET("/Flow", h.ListFlowVersions)
	router.GET("/Flow/:id", h.GetFlowVersion)
	router.POST("/Flow", h.CreateFlowVersion)
	router.PATCH("/Flow/:id", h.UpdateFlowVersion)
	router.DELETE("/Flow/:id", h.DeleteFlowVersion)
	router.POST("/Flow/:id/activate", h.ActivateFlowVersion)
	router.POST("/Flow/:id/deactivate", h.DeactivateFlowVersion)
}
