package handler

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"

	"github.com/sundynix/sundynix-gateway/internal/store"
)

// AgentList: GET /api/v1/agents —— 当前活跃工作区(space)的全部编排（共享：同空间成员都可见，含创建人）。
func (h *Handler) AgentList(c *gin.Context) {
	rows, err := h.db.ListAgents(c.Request.Context(), spaceID(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 {
		creator := r.CreatorName
		if creator == "" {
			creator = r.CreatorMail
		}
		out = append(out, gin.H{"name": r.Name, "graph": r.Graph, "updated_at": r.UpdatedAt,
			"owner": r.Owner, "creator": creator, "mine": r.Owner == userID(c)})
	}
	c.JSON(http.StatusOK, gin.H{"agents": out})
}

// AgentSave: POST /api/v1/agents {name, graph} —— 保存/更新编排到当前空间（空间内重名覆盖）。
// 已由 RequireSpaceRole(member) 门控：viewer 只读进不来。
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
	}
	name := strings.TrimSpace(body.Name)
	// 覆盖他人建的编排需 admin/owner；member 只能改自己建的（新建不受限）。
	if existing, _ := h.db.GetAgent(c.Request.Context(), spaceID(c), name); existing != nil &&
		existing.Owner != userID(c) && store.RoleRank(h.db.SpaceMemberRole(c.Request.Context(), spaceID(c), userID(c))) < store.RoleRank(store.RoleAdmin) {
		c.JSON(http.StatusForbidden, gin.H{"error": "该编排由他人创建，仅管理员可覆盖"})
		return
	}
	if err := h.db.SaveAgent(c.Request.Context(), spaceID(c), userID(c), name, body.Graph); err != nil {
		c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"name": name})
}

// AgentDelete: DELETE /api/v1/agents?name= —— 删除当前空间的一份编排。
// 删他人建的需 admin/owner；member 只能删自己建的。
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
	}
	existing, err := h.db.GetAgent(c.Request.Context(), spaceID(c), name)
	if err != nil {
		c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
		return
	}
	if existing == nil {
		c.JSON(http.StatusOK, gin.H{"status": "ok"}) // 已不存在，幂等
		return
	}
	if existing.Owner != userID(c) && store.RoleRank(h.db.SpaceMemberRole(c.Request.Context(), spaceID(c), userID(c))) < store.RoleRank(store.RoleAdmin) {
		c.JSON(http.StatusForbidden, gin.H{"error": "该编排由他人创建，仅管理员可删除"})
		return
	}
	if err := h.db.DeleteAgent(c.Request.Context(), spaceID(c), name); err != nil {
		c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
