package admin

import (
	"net/http"
	"verification-platform-backend/internal/database"
	"verification-platform-backend/internal/model"

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

func SetupSmsConfigRoutes(r *gin.RouterGroup) {
	smsConfigs := r.Group("/sms-configs")
	{
		smsConfigs.GET("", handleGetSmsConfigs)
		smsConfigs.POST("", handleCreateSmsConfig)
		smsConfigs.GET("/:id", handleGetSmsConfig)
		smsConfigs.PUT("/:id", handleUpdateSmsConfig)
		smsConfigs.DELETE("/:id", handleDeleteSmsConfig)
		smsConfigs.PUT("/:id/status", handleUpdateSmsConfigStatus)
		smsConfigs.POST("/:id/test", handleTestSmsConfig)
		smsConfigs.PUT("/batch/status", handleBatchUpdateSmsConfigStatus)
		smsConfigs.DELETE("/batch", handleBatchDeleteSmsConfigs)
	}
}

func handleGetSmsConfigs(c *gin.Context) {
	var configs []model.SmsConfig
	database.DB.Order("id desc").Find(&configs)

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": gin.H{
			"sms_configs": configs,
		},
	})
}

type CreateSmsConfigRequest struct {
	Name   string `json:"name" binding:"required"`
	Type   string `json:"type" binding:"required"`
	Config string `json:"config"`
	Status string `json:"status"`
	Remark string `json:"remark"`
}

func handleCreateSmsConfig(c *gin.Context) {
	var req CreateSmsConfigRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的请求数据",
		})
		return
	}

	status := "active"
	if req.Status != "" {
		status = req.Status
	}

	config := model.SmsConfig{
		Name:   req.Name,
		Type:   req.Type,
		Config: req.Config,
		Status: status,
		Remark: req.Remark,
	}

	if err := database.DB.Create(&config).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "创建失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "创建成功",
		"data":    config,
	})
}

func handleGetSmsConfig(c *gin.Context) {
	id := c.Param("id")

	var config model.SmsConfig
	if err := database.DB.First(&config, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code":    404,
			"message": "短信配置不存在",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": config,
	})
}

type UpdateSmsConfigRequest struct {
	Name   string `json:"name"`
	Type   string `json:"type"`
	Config string `json:"config"`
	Remark string `json:"remark"`
}

func handleUpdateSmsConfig(c *gin.Context) {
	id := c.Param("id")

	var config model.SmsConfig
	if err := database.DB.First(&config, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code":    404,
			"message": "短信配置不存在",
		})
		return
	}

	var req UpdateSmsConfigRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的请求数据",
		})
		return
	}

	if req.Name != "" {
		config.Name = req.Name
	}
	if req.Type != "" {
		config.Type = req.Type
	}
	if req.Config != "" {
		config.Config = req.Config
	}
	config.Remark = req.Remark

	if err := database.DB.Save(&config).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "更新失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "更新成功",
		"data":    config,
	})
}

func handleDeleteSmsConfig(c *gin.Context) {
	id := c.Param("id")

	var config model.SmsConfig
	if err := database.DB.First(&config, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code":    404,
			"message": "短信配置不存在",
		})
		return
	}

	if err := database.DB.Delete(&config).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "删除失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "删除成功",
	})
}

type UpdateSmsConfigStatusRequest struct {
	Status string `json:"status" binding:"required"`
}

func handleUpdateSmsConfigStatus(c *gin.Context) {
	id := c.Param("id")

	var config model.SmsConfig
	if err := database.DB.First(&config, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code":    404,
			"message": "短信配置不存在",
		})
		return
	}

	var req UpdateSmsConfigStatusRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的请求数据",
		})
		return
	}

	config.Status = req.Status
	if err := database.DB.Save(&config).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "更新失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "更新成功",
	})
}

type TestSmsConfigRequest struct {
	Phone string `json:"phone" binding:"required"`
}

func handleTestSmsConfig(c *gin.Context) {
	id := c.Param("id")

	var config model.SmsConfig
	if err := database.DB.First(&config, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code":    404,
			"message": "短信配置不存在",
		})
		return
	}

	var req TestSmsConfigRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "请输入有效的手机号码",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "测试短信已发送",
	})
}

type BatchUpdateSmsConfigStatusRequest struct {
	IDs    []uint `json:"ids"`
	Status string `json:"status"`
}

func handleBatchUpdateSmsConfigStatus(c *gin.Context) {
	var req BatchUpdateSmsConfigStatusRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "参数错误",
		})
		return
	}

	if req.Status != "active" && req.Status != "inactive" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的状态",
		})
		return
	}

	if len(req.IDs) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "请选择要更新的短信配置",
		})
		return
	}

	if err := database.DB.Model(&model.SmsConfig{}).Where("id IN ?", req.IDs).Update("status", req.Status).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "批量更新失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "批量更新成功",
	})
}

type BatchDeleteSmsConfigsRequest struct {
	IDs []uint `json:"ids"`
}

func handleBatchDeleteSmsConfigs(c *gin.Context) {
	var req BatchDeleteSmsConfigsRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "参数错误",
		})
		return
	}

	if len(req.IDs) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "请选择要删除的短信配置",
		})
		return
	}

	if err := database.DB.Where("id IN ?", req.IDs).Delete(&model.SmsConfig{}).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "批量删除失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "批量删除成功",
	})
}
