package api

import (
	"net/http"

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

func (s *Server) outboundOverview(c *gin.Context) {
	data, err := s.app.OutboundOverview(c.Request.Context())
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, data)
}

type selectOutboundReq struct {
	Proxy string `json:"proxy"`
}

func (s *Server) selectOutboundGroup(c *gin.Context) {
	name := c.Param("name")
	var req selectOutboundReq
	if err := c.ShouldBindJSON(&req); err != nil || req.Proxy == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "proxy required"})
		return
	}
	if err := s.app.SelectOutboundGroup(c.Request.Context(), name, req.Proxy); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"ok": true})
}

type defaultPolicyReq struct {
	Policy string `json:"policy"`
}

func (s *Server) setDefaultPolicy(c *gin.Context) {
	var req defaultPolicyReq
	if err := c.ShouldBindJSON(&req); err != nil || req.Policy == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "policy required"})
		return
	}
	if err := s.app.SetDefaultPolicy(c.Request.Context(), req.Policy); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	s.syncMihomoClient(c.Request.Context())
	c.JSON(http.StatusOK, gin.H{"ok": true})
}
