package handlers

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"mengyastore-backend/internal/storage"
)

type MaintenancePayload struct {
	Maintenance bool   `json:"maintenance"`
	Reason      string `json:"reason"`
}

// SetMaintenance 设置站点维护模式。
// @Summary 设置维护模式
// @Tags 管理端-站点
// @Accept json
// @Produce json
// @Security AdminToken
// @Param body body MaintenancePayload true "维护开关与原因"
// @Success 200 {object} SwaggerMaintenanceWrap
// @Failure 400 {object} SwaggerErrorBody
// @Failure 401 {object} SwaggerErrorBody
// @Failure 500 {object} SwaggerErrorBody
// @Router /api/admin/site/maintenance [post]
func (h *AdminHandler) SetMaintenance(c *gin.Context) {
	if !h.requireAdmin(c) {
		return
	}
	var payload MaintenancePayload
	if err := c.ShouldBindJSON(&payload); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
		return
	}
	if err := h.siteStore.SetMaintenance(payload.Maintenance, payload.Reason); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"data": gin.H{
			"maintenance": payload.Maintenance,
			"reason":      payload.Reason,
		},
	})
}

// GetSMTPConfig 获取 SMTP 配置（密码脱敏）。
// @Summary 获取 SMTP 配置
// @Tags 管理端-站点
// @Produce json
// @Security AdminToken
// @Success 200 {object} SwaggerSMTPWrap
// @Failure 401 {object} SwaggerErrorBody
// @Failure 500 {object} SwaggerErrorBody
// @Router /api/admin/site/smtp [get]
func (h *AdminHandler) GetSMTPConfig(c *gin.Context) {
	if !h.requireAdmin(c) {
		return
	}
	cfg, err := h.siteStore.GetSMTPConfig()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	// 响应中对密码脱敏处理
	masked := cfg
	if masked.Password != "" {
		masked.Password = "••••••••"
	}
	c.JSON(http.StatusOK, gin.H{"data": masked})
}

// SetSMTPConfig 保存 SMTP 配置。
// @Summary 保存 SMTP 配置
// @Tags 管理端-站点
// @Accept json
// @Produce json
// @Security AdminToken
// @Param body body storage.SMTPConfig true "SMTP 字段"
// @Success 200 {object} SwaggerStringOKBody
// @Failure 400 {object} SwaggerErrorBody
// @Failure 401 {object} SwaggerErrorBody
// @Failure 500 {object} SwaggerErrorBody
// @Router /api/admin/site/smtp [post]
func (h *AdminHandler) SetSMTPConfig(c *gin.Context) {
	if !h.requireAdmin(c) {
		return
	}
	var payload storage.SMTPConfig
	if err := c.ShouldBindJSON(&payload); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数有误"})
		return
	}
	// 若密码为脱敏占位符，则保留数据库中原有的密码
	if payload.Password == "••••••••" {
		existing, _ := h.siteStore.GetSMTPConfig()
		payload.Password = existing.Password
	}
	if err := h.siteStore.SetSMTPConfig(payload); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": "ok"})
}
