package handlers

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"switchboard-core/models"
	"switchboard-core/store"
	"switchboard-core/workflow"
)

// ── Signoff Handlers (v0.3.4) ─────────────────

// WorkflowSignoffHandler manages signoff HTTP endpoints.
type WorkflowSignoffHandler struct {
	engine *workflow.Engine
	stores store.Stores
}

// NewWorkflowSignoffHandler creates a signoff handler.
func NewWorkflowSignoffHandler(engine *workflow.Engine, stores store.Stores) *WorkflowSignoffHandler {
	return &WorkflowSignoffHandler{engine: engine, stores: stores}
}

// Submit records a signoff (approve/reject) for the current stage of an instance.
// POST /api/v1/instances/:iid/signoffs
func (h *WorkflowSignoffHandler) Submit(c *gin.Context) {
	userID := c.GetString("user_id")
	instanceID := c.Param("iid")

	var body struct {
		Decision string `json:"decision" binding:"required,oneof=approve reject"`
		Comment  string `json:"comment"`
	}
	if err := c.ShouldBindJSON(&body); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	so, err := h.engine.SubmitSignoff(c.Request.Context(), instanceID, userID, body.Decision, body.Comment)
	if err != nil {
		c.JSON(http.StatusConflict, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, so)
}

// List returns signoffs for the current stage of an instance.
// GET /api/v1/instances/:iid/signoffs
func (h *WorkflowSignoffHandler) List(c *gin.Context) {
	instanceID := c.Param("iid")

	// Get the instance to determine current stage
	inst, err := h.stores.Workflows.GetInstance(c.Request.Context(), instanceID)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "instance not found"})
		return
	}

	signoffs, err := h.stores.Workflows.ListSignoffs(c.Request.Context(), instanceID, inst.CurrentStage)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
		return
	}
	if signoffs == nil {
		signoffs = []models.WorkflowSignoff{}
	}

	c.JSON(http.StatusOK, gin.H{"data": signoffs})
}
