package handlers

import (
	"encoding/json"

	"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) {
	// 获取所有设置
	settingsMap, err := repositories.GetAllSettings()
	if err != nil {
		utils.ServerError(c, err)
		return
	}

	// 只返回前端需要的公开配置项
	publicSettings := make(map[string]string)
	publicKeys := []string{
		"site_title", "site_description", "site_author", "site_keywords",
		"visible_menus", "posts_per_page", "works_per_page", "snippets_per_page",
		"footer_icp", "contact_email",
	}

	for _, key := range publicKeys {
		if value, exists := settingsMap[key]; exists {
			publicSettings[key] = value
		}
	}

	utils.Success(c, publicSettings)
}

// 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) {
	// 读取原始 body
	body, err := c.GetRawData()
	if err != nil {
		utils.Error(c, 400, "Invalid request")
		return
	}

	// 检查 JSON 是否包含 keyName 字段来判断是 Setting 对象还是 map
	var temp map[string]interface{}
	if err := json.Unmarshal(body, &temp); err == nil {
		if _, ok := temp["keyName"]; ok {
			// 如果包含 keyName 字段，认为是 Setting 对象
			var setting models.Setting
			if err := json.Unmarshal(body, &setting); err != nil {
				utils.Error(c, 400, "Invalid request")
				return
			}
			if setting.KeyName == "" {
				utils.Error(c, 400, "keyName is required")
				return
			}
			if err := repositories.UpdateSetting(&setting); err != nil {
				utils.ServerError(c, err)
				return
			}
			utils.SuccessWithMsg(c, "Setting updated successfully", nil)
			return
		}
	}

	// 如果不包含 keyName，认为是批量更新的 map
	var req map[string]string
	if err := json.Unmarshal(body, &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)
}
