package handlers

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"sproutclaw-web/internal/db"
	"sproutclaw-web/internal/models"
)

// RegisterWebuiConfig registers WebUI config and avatar routes.
func RegisterWebuiConfig(r *gin.RouterGroup, database *db.DB) {
	r.GET("/avatars", handleGetAvatars(database))
	r.GET("/webui/config", handleGetWebuiConfig(database))
	r.POST("/webui/config", handleSetWebuiConfig(database))
	r.POST("/webui/config/delete", handleDeleteWebuiConfig(database))
}

func handleGetAvatars(database *db.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		user, _ := database.GetConfig("userAvatarUrl")
		agent, _ := database.GetConfig("agentAvatarUrl")
		c.JSON(http.StatusOK, models.AvatarsResponse{
			UserAvatarURL:  normalizeAvatarURL(user),
			AgentAvatarURL: normalizeAvatarURL(agent),
		})
	}
}

func normalizeAvatarURL(u string) string {
	if strings.HasPrefix(u, "http://") || strings.HasPrefix(u, "https://") {
		return u
	}
	return ""
}

func handleGetWebuiConfig(database *db.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		key := c.Query("key")
		if key != "" {
			val, _ := database.GetConfig(key)
			c.JSON(http.StatusOK, gin.H{"key": key, "value": val})
			return
		}
		all, err := database.AllConfig()
		if err != nil {
			c.JSON(http.StatusInternalServerError, models.ErrorResponse{Error: err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"entries": all})
	}
}

func handleSetWebuiConfig(database *db.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		var req models.WebuiConfigSetRequest
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, models.ErrorResponse{Error: err.Error()})
			return
		}
		if req.Entries != nil {
			for k, v := range req.Entries {
				if err := database.SetConfig(k, v); err != nil {
					c.JSON(http.StatusInternalServerError, models.ErrorResponse{Error: err.Error()})
					return
				}
			}
		} else if req.Key != "" {
			if err := database.SetConfig(req.Key, req.Value); err != nil {
				c.JSON(http.StatusInternalServerError, models.ErrorResponse{Error: err.Error()})
				return
			}
		}
		c.JSON(http.StatusOK, models.OKResponse{OK: true})
	}
}

func handleDeleteWebuiConfig(database *db.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		var req models.WebuiConfigDeleteRequest
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, models.ErrorResponse{Error: err.Error()})
			return
		}
		if err := database.DeleteConfig(req.Key); err != nil {
			c.JSON(http.StatusInternalServerError, models.ErrorResponse{Error: err.Error()})
			return
		}
		c.JSON(http.StatusOK, models.OKResponse{OK: true})
	}
}
