package handlers

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"mengyaping-backend/config"
	"mengyaping-backend/models"
	"mengyaping-backend/services"
	"mengyaping-backend/storage"
)

// SettingsHandler 监控与系统配置（公开可读、管理端可写）
type SettingsHandler struct {
	monitor *services.MonitorService
}

// NewSettingsHandler 创建配置处理器
func NewSettingsHandler() *SettingsHandler {
	return &SettingsHandler{
		monitor: services.GetMonitorService(),
	}
}

// GetPublicMonitorSettings 公开：当前全局检测周期与可选值
func (h *SettingsHandler) GetPublicMonitorSettings(c *gin.Context) {
	cfg := config.GetConfig()
	c.JSON(http.StatusOK, models.APIResponse{
		Code:    0,
		Message: "success",
		Data: gin.H{
			"interval_minutes":         int(cfg.Monitor.Interval.Minutes()),
			"allowed_interval_minutes": config.AllowedMonitorIntervalMinutes,
		},
	})
}

// GetAdminConfig 管理端：监控相关配置（只读字段供面板展示）
func (h *SettingsHandler) GetAdminConfig(c *gin.Context) {
	cfg := config.GetConfig()
	c.JSON(http.StatusOK, models.APIResponse{
		Code:    0,
		Message: "success",
		Data: gin.H{
			"interval_minutes":         int(cfg.Monitor.Interval.Minutes()),
			"allowed_interval_minutes": config.AllowedMonitorIntervalMinutes,
			"timeout_seconds":          int(cfg.Monitor.Timeout.Seconds()),
			"retry_count":              cfg.Monitor.RetryCount,
			"history_days":             cfg.Monitor.HistoryDays,
		},
	})
}

type putAdminMonitorConfigRequest struct {
	IntervalMinutes int `json:"interval_minutes" binding:"required"`
}

// PutAdminMonitorConfig 更新全局检测周期并持久化、应用新调度
func (h *SettingsHandler) PutAdminMonitorConfig(c *gin.Context) {
	var req putAdminMonitorConfigRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, models.APIResponse{
			Code:    400,
			Message: "参数错误: " + err.Error(),
		})
		return
	}

	if err := storage.GetStorage().SetMonitorIntervalMinutes(req.IntervalMinutes); err != nil {
		c.JSON(http.StatusBadRequest, models.APIResponse{
			Code:    400,
			Message: err.Error(),
		})
		return
	}

	h.monitor.Reschedule()

	c.JSON(http.StatusOK, models.APIResponse{
		Code:    0,
		Message: "已更新检测周期",
		Data: gin.H{
			"interval_minutes": req.IntervalMinutes,
		},
	})
}
