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"`
}

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,
		},
	})
}

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})
}

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"})
}
