package server

import (
	"net/http"

	"gophergate/internal/db"

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

func (s *Server) handleGetModelGroups(c *gin.Context) {
	var groups []db.ModelGroup
	if err := s.database.Select(&groups, "SELECT * FROM model_groups ORDER BY id"); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	if groups == nil {
		groups = []db.ModelGroup{}
	}
	c.JSON(http.StatusOK, SuccessResponse(groups))
}

func (s *Server) handleCreateModelGroup(c *gin.Context) {
	var group db.ModelGroup
	if err := c.ShouldBindJSON(&group); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	_, err := s.database.Exec(`
		INSERT INTO model_groups (id, strategy, selector_model, targets, complexity_threshold, heuristic_rules)
		VALUES (?, ?, ?, ?, ?, ?)`,
		group.ID, group.Strategy, group.SelectorModel, group.Targets,
		group.ComplexityThreshold, group.HeuristicRules)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	s.refreshRouter()
	c.JSON(http.StatusCreated, SuccessResponse(group))
}

func (s *Server) handleUpdateModelGroup(c *gin.Context) {
	id := c.Param("id")
	var group db.ModelGroup
	if err := c.ShouldBindJSON(&group); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	_, err := s.database.Exec(`
		UPDATE model_groups SET strategy=?, selector_model=?, targets=?, complexity_threshold=?, heuristic_rules=?, updated_at=CURRENT_TIMESTAMP
		WHERE id=?`,
		group.Strategy, group.SelectorModel, group.Targets,
		group.ComplexityThreshold, group.HeuristicRules, id)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	s.refreshRouter()
	c.JSON(http.StatusOK, SuccessResponse(group))
}

func (s *Server) handleDeleteModelGroup(c *gin.Context) {
	id := c.Param("id")
	_, err := s.database.Exec("DELETE FROM model_groups WHERE id=?", id)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	s.refreshRouter()
	c.JSON(http.StatusOK, gin.H{"status": "deleted"})
}
