package handler

import (
	"net/http"

	"git.zkcoi.com/zkcoi/meshray/internal/model"
	"git.zkcoi.com/zkcoi/meshray/internal/service"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// ServiceHandler 服务管理 Handler
type ServiceHandler struct {
	serviceService *service.ServiceService
	logger         *zap.Logger
}

// NewServiceHandler 创建 Service Handler
func NewServiceHandler(serviceService *service.ServiceService, logger *zap.Logger) *ServiceHandler {
	return &ServiceHandler{
		serviceService: serviceService,
		logger:         logger,
	}
}

// ListServices 获取服务列表
func (h *ServiceHandler) ListServices(c *gin.Context) {
	serverType := c.Query("type")
	services, err := h.serviceService.ListServices(serverType)
	if err != nil {
		h.logger.Error("获取服务列表失败", zap.Error(err))
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取服务列表失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": services})
}

// GetService 获取服务详情
func (h *ServiceHandler) GetService(c *gin.Context) {
	id := c.Param("id")
	if id == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "缺少 ID"})
		return
	}

	service, err := h.serviceService.GetServiceByID(id)
	if err != nil {
		h.logger.Error("获取服务失败", zap.Error(err))
		c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": service})
}

// CreateService 创建服务
func (h *ServiceHandler) CreateService(c *gin.Context) {
	var req model.Service
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数错误"})
		return
	}

	service, err := h.serviceService.CreateService(&req)
	if err != nil {
		h.logger.Error("创建服务失败", zap.Error(err))
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	h.logger.Info("服务创建成功", zap.String("name", service.Name))
	c.JSON(http.StatusOK, gin.H{"data": service})
}

// UpdateService 更新服务
func (h *ServiceHandler) UpdateService(c *gin.Context) {
	id := c.Param("id")
	if id == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "缺少 ID"})
		return
	}

	var updates map[string]interface{}
	if err := c.ShouldBindJSON(&updates); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数错误"})
		return
	}

	service, err := h.serviceService.UpdateService(id, updates)
	if err != nil {
		h.logger.Error("更新服务失败", zap.Error(err))
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	h.logger.Info("服务更新成功", zap.String("id", service.ID))
	c.JSON(http.StatusOK, gin.H{"data": service})
}

// DeleteService 删除服务
func (h *ServiceHandler) DeleteService(c *gin.Context) {
	id := c.Param("id")
	if id == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "缺少 ID"})
		return
	}

	if err := h.serviceService.DeleteService(id); err != nil {
		h.logger.Error("删除服务失败", zap.Error(err))
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	h.logger.Info("服务删除成功", zap.String("id", id))
	c.JSON(http.StatusOK, gin.H{"message": "服务已删除"})
}

// TestServiceConnectivity 测试服务连通性
func (h *ServiceHandler) TestServiceConnectivity(c *gin.Context) {
	id := c.Param("id")
	if id == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "缺少 ID"})
		return
	}

	status, err := h.serviceService.TestServiceConnectivity(id)
	if err != nil {
		h.logger.Error("测试连通性失败", zap.Error(err))
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": gin.H{"status": status}})
}

// GetServiceSchema 获取服务 Schema（支持的协议类型）
func (h *ServiceHandler) GetServiceSchema(c *gin.Context) {
	schema := gin.H{
		"protocols": []gin.H{
			{
				"type":        "http",
				"label":       "HTTP 服务",
				"description": "超文本传输协议，用于 Web 服务",
				"defaultPort": 80,
			},
			{
				"type":        "https",
				"label":       "HTTPS 服务",
				"description": "安全的 HTTP 协议，用于加密 Web 服务",
				"defaultPort": 443,
			},
			{
				"type":        "tcp",
				"label":       "TCP 服务",
				"description": "传输控制协议，面向连接的可靠传输",
				"defaultPort": 0,
			},
			{
				"type":        "udp",
				"label":       "UDP 服务",
				"description": "用户数据报协议，无连接的快速传输",
				"defaultPort": 0,
			},
			{
				"type":        "ssh",
				"label":       "SSH 服务",
				"description": "安全外壳协议，用于远程登录",
				"defaultPort": 22,
			},
			{
				"type":        "rdp",
				"label":       "RDP 服务",
				"description": "远程桌面协议，用于 Windows 远程桌面",
				"defaultPort": 3389,
			},
			{
				"type":        "vnc",
				"label":       "VNC 服务",
				"description": "虚拟网络计算，用于图形化远程桌面",
				"defaultPort": 5900,
			},
			{
				"type":        "custom",
				"label":       "自定义服务",
				"description": "用户自定义的其他服务类型",
				"defaultPort": 0,
			},
		},
	}
	c.JSON(http.StatusOK, gin.H{"data": schema})
}
