package handlers

import (
	"github.com/gin-gonic/gin"
	"github.com/niangaodev/art-code/models"
	"github.com/niangaodev/art-code/repositories"
	"github.com/niangaodev/art-code/utils"
)

// GetSettings 获取设置
func GetSettings(c *gin.Context) {
	// 目前没有公开的设置接口，保留作为扩展
	// 如果需要公开设置，可以类似处理
	utils.Success(c, gin.H{})
}

// AdminGetSettings 获取所有设置
func AdminGetSettings(c *gin.Context) {
	settings, err := repositories.GetSettings()
	if err != nil {
		utils.ServerError(c, err)
		return
	}
	// Ensure not nil
	if settings == nil {
		utils.Success(c, []interface{}{})
	} else {
		utils.Success(c, settings)
	}
}

// AdminUpdateSettings 批量更新设置
func AdminUpdateSettings(c *gin.Context) {
	var req map[string]string
	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Error(c, 400, "Invalid request")
		return
	}

	if err := repositories.UpdateSettings(req); err != nil {
		utils.ServerError(c, err)
		return
	}

	utils.SuccessWithMsg(c, "Settings updated successfully", nil)
}

// AdminCreateSetting 创建系统配置
func AdminCreateSetting(c *gin.Context) {
	var setting models.Setting
	if err := c.ShouldBindJSON(&setting); err != nil {
		utils.Error(c, 400, "Invalid request")
		return
	}

	if err := repositories.CreateSetting(&setting); err != nil {
		utils.ServerError(c, err)
		return
	}

	utils.SuccessWithMsg(c, "Setting created successfully", gin.H{"id": setting.ID})
}

// AdminUpdateSetting 更新单个系统配置
func AdminUpdateSetting(c *gin.Context) {
	// keyName := c.Param("id") // Param is :id, but repo uses key_name
	// Assuming frontend sends key_name in body or we use ID.
	// But repo `UpdateSetting` uses key_name.
	// Let's rely on body for now.

	var setting models.Setting
	if err := c.ShouldBindJSON(&setting); err != nil {
		utils.Error(c, 400, "Invalid request")
		return
	}

	if err := repositories.UpdateSetting(&setting); err != nil {
		utils.ServerError(c, err)
		return
	}

	utils.SuccessWithMsg(c, "Setting updated successfully", nil)
}

// AdminDeleteSetting 删除系统配置
func AdminDeleteSetting(c *gin.Context) {
	keyName := c.Param("key")
	if err := repositories.DeleteSetting(keyName); err != nil {
		utils.ServerError(c, err)
		return
	}
	utils.SuccessWithMsg(c, "Setting deleted successfully", nil)
}
