package admin

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

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

func SetupEmailConfigRoutes(r *gin.RouterGroup) {
	emailConfigs := r.Group("/email-configs")
	{
		emailConfigs.GET("", handleGetSystemEmailConfigs)
		emailConfigs.POST("", handleCreateSystemEmailConfig)
		emailConfigs.GET("/:id", handleGetSystemEmailConfig)
		emailConfigs.PUT("/:id", handleUpdateSystemEmailConfig)
		emailConfigs.DELETE("/:id", handleDeleteSystemEmailConfig)
		emailConfigs.PUT("/:id/status", handleUpdateSystemEmailConfigStatus)
		emailConfigs.POST("/:id/test", handleTestSystemEmailConfig)
		emailConfigs.PUT("/batch/status", handleBatchUpdateEmailConfigStatus)
		emailConfigs.DELETE("/batch", handleBatchDeleteEmailConfigs)
	}
}

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

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

type CreateSystemEmailConfigRequest struct {
	Name         string `json:"name" binding:"required"`
	SMTPHost     string `json:"smtp_host" binding:"required"`
	SMTPPort     int    `json:"smtp_port" binding:"required"`
	SMTPUser     string `json:"smtp_user" binding:"required"`
	SMTPPassword string `json:"smtp_password"`
	SMTPFrom     string `json:"smtp_from" binding:"required"`
	SMTPFromName string `json:"smtp_from_name"`
	Encryption   string `json:"encryption"`
	Status       string `json:"status"`
	Remark       string `json:"remark"`
}

func handleCreateSystemEmailConfig(c *gin.Context) {
	var req CreateSystemEmailConfigRequest
	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
	}

	encryption := "tls"
	if req.Encryption != "" {
		encryption = req.Encryption
	}

	config := model.EmailConfig{
		Name:         req.Name,
		SMTPHost:     req.SMTPHost,
		SMTPPort:     req.SMTPPort,
		SMTPUser:     req.SMTPUser,
		SMTPPassword: req.SMTPPassword,
		SMTPFrom:     req.SMTPFrom,
		SMTPFromName: req.SMTPFromName,
		Encryption:   encryption,
		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 handleGetSystemEmailConfig(c *gin.Context) {
	id := c.Param("id")

	var config model.EmailConfig
	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 UpdateSystemEmailConfigRequest struct {
	Name         string `json:"name"`
	SMTPHost     string `json:"smtp_host"`
	SMTPPort     int    `json:"smtp_port"`
	SMTPUser     string `json:"smtp_user"`
	SMTPPassword string `json:"smtp_password"`
	SMTPFrom     string `json:"smtp_from"`
	SMTPFromName string `json:"smtp_from_name"`
	Encryption   string `json:"encryption"`
	Remark       string `json:"remark"`
}

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

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

	var req UpdateSystemEmailConfigRequest
	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.SMTPHost != "" {
		config.SMTPHost = req.SMTPHost
	}
	if req.SMTPPort != 0 {
		config.SMTPPort = req.SMTPPort
	}
	if req.SMTPUser != "" {
		config.SMTPUser = req.SMTPUser
	}
	if req.SMTPPassword != "" {
		config.SMTPPassword = req.SMTPPassword
	}
	if req.SMTPFrom != "" {
		config.SMTPFrom = req.SMTPFrom
	}
	config.SMTPFromName = req.SMTPFromName
	if req.Encryption != "" {
		config.Encryption = req.Encryption
	}
	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 handleDeleteSystemEmailConfig(c *gin.Context) {
	id := c.Param("id")

	var config model.EmailConfig
	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 UpdateSystemEmailConfigStatusRequest struct {
	Status string `json:"status" binding:"required"`
}

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

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

	var req UpdateSystemEmailConfigStatusRequest
	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 TestSystemEmailConfigRequest struct {
	Email string `json:"email" binding:"required,email"`
}

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

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

	var req TestSystemEmailConfigRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "请输入有效的邮箱地址",
		})
		return
	}

	emailService := service.NewEmailService()
	emailConfig := service.EmailConfig{
		Host:      config.SMTPHost,
		Port:      config.SMTPPort,
		User:      config.SMTPUser,
		Password:  config.SMTPPassword,
		FromEmail: config.SMTPFrom,
		FromName:  config.SMTPFromName,
		UseSSL:    config.Encryption == "ssl",
	}

	if err := emailService.SendTestEmail(emailConfig, req.Email, config.Name); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": fmt.Sprintf("发送失败: %v", err),
		})
		return
	}

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

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

func handleBatchUpdateEmailConfigStatus(c *gin.Context) {
	var req BatchUpdateEmailConfigStatusRequest
	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.EmailConfig{}).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 BatchDeleteEmailConfigsRequest struct {
	IDs []uint `json:"ids"`
}

func handleBatchDeleteEmailConfigs(c *gin.Context) {
	var req BatchDeleteEmailConfigsRequest
	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.EmailConfig{}).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "批量删除失败",
		})
		return
	}

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