package handler

import (
	"net/http"

	"git.zkcoi.com/zkcoi/meshray/internal/service"
	"github.com/gin-gonic/gin"
)

// IPDetectHandler IP 检测处理器
type IPDetectHandler struct {
	ipDetection *service.IPDetectionService
}

// NewIPDetectHandler 创建 IP 检测处理器
func NewIPDetectHandler() *IPDetectHandler {
	return &IPDetectHandler{
		ipDetection: service.NewIPDetectionService(),
	}
}

// DetectIP 检测公网 IP 地址
// @Summary 检测公网 IP 地址
// @Tags DDNS
// @Accept json
// @Produce json
// @Param record_type query string false "记录类型 (A|AAAA)" default(A)
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/services/ddns/detect-ip [get]
func (h *IPDetectHandler) DetectIP(c *gin.Context) {
	recordType := c.DefaultQuery("record_type", "A")

	if recordType != "A" && recordType != "AAAA" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "不支持的记录类型，仅支持 A 或 AAAA",
		})
		return
	}

	ip, err := h.ipDetection.DetectIP(recordType)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "检测失败：" + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"data": gin.H{
			"ip": ip,
		},
		"message": "检测成功",
	})
}
