package handler

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

// AgentList: GET /api/v1/agents —— 当前用户保存的全部 Agent 编排（owner 隔离，最近在前）。
func (h *Handler) AgentList(c *gin.Context) {
	rows, err := h.db.ListAgents(c.Request.Context(), userID(c))
	if err != nil {
		c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
		return
	}
	out := make([]gin.H, 0, len(rows))
	for _, r := range rows {
		out = append(out, gin.H{"name": r.Name, "graph": r.Graph, "updated_at": r.UpdatedAt})
	}
	c.JSON(http.StatusOK, gin.H{"agents": out})
}

// AgentSave: POST /api/v1/agents {name, graph} —— 保存/更新一份编排（graph 为 {nodes,edges} JSON）。
func (h *Handler) AgentSave(c *gin.Context) {
	var body struct {
		Name  string `json:"name"`
		Graph string `json:"graph"`
	}
	if err := c.ShouldBindJSON(&body); err != nil || strings.TrimSpace(body.Name) == "" || strings.TrimSpace(body.Graph) == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "name/graph required"})
		return
	}
	if err := h.db.SaveAgent(c.Request.Context(), userID(c), strings.TrimSpace(body.Name), body.Graph); err != nil {
		c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"name": strings.TrimSpace(body.Name)})
}

// AgentDelete: DELETE /api/v1/agents?name= —— 删除一份编排。
func (h *Handler) AgentDelete(c *gin.Context) {
	name := strings.TrimSpace(c.Query("name"))
	if name == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "name required"})
		return
	}
	if err := h.db.DeleteAgent(c.Request.Context(), userID(c), name); err != nil {
		c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
