package handlers

import (
	"encoding/json"
	"strings"

	"github.com/gin-gonic/gin"
	"wa-assistant/backend/models"
)

func PreviewFlow(c *gin.Context) {
	if _, ok := resolveAgent(c); !ok {
		return
	}
	var req struct {
		Config   models.Flow `json:"config"`
		NodeID   string      `json:"node_id"`
		Text     string      `json:"text"`
		ActionID string      `json:"action_id"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(400, gin.H{"error": "Data simulasi tidak valid"})
		return
	}
	var s flowStructure
	if err := json.Unmarshal([]byte(req.Config.Structure), &s); err != nil {
		c.JSON(400, gin.H{"error": "Struktur alur tidak valid"})
		return
	}
	if err := validateFlowForEditing(s); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	if err := validateFlowDisplay(req.Config.DisplayMode, s); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	if strings.TrimSpace(req.Config.Trigger) == "" || len([]rune(req.Config.Trigger)) > 64 || reservedFlowCode(req.Config.Trigger) || len([]rune(req.Text)) > 4000 {
		c.JSON(400, gin.H{"error": "Periksa kata pemicu dan panjang pesan simulasi"})
		return
	}
	if req.Config.MatchType != "exact" && req.Config.MatchType != "prefix" && req.Config.MatchType != "contains" {
		c.JSON(400, gin.H{"error": "Cara cocok pemicu tidak valid"})
		return
	}
	if req.Config.DelayMin < 0 || req.Config.DelayMax > 30 || req.Config.DelayMin > req.Config.DelayMax {
		c.JSON(400, gin.H{"error": "Jeda balasan harus 0–30 detik dan minimum tidak boleh melebihi maksimum"})
		return
	}
	step := advanceFlow(req.Config, s, req.NodeID, req.Text, req.ActionID)
	buttons := make([]gin.H, 0, len(step.buttons))
	for _, button := range step.buttons {
		buttons = append(buttons, gin.H{"id": button.ID, "label": button.Text})
	}
	c.JSON(200, gin.H{"data": gin.H{
		"handled": step.handled, "reply": step.reply, "fallback": step.fallback,
		"node_id": step.nodeID, "handoff": step.handoff, "buttons": buttons,
	}})
}
