package handlers

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"chat-switchboard/models"
	"chat-switchboard/store"
)

// ModelPrefsHandler handles user model preference endpoints.
type ModelPrefsHandler struct {
	stores store.Stores
}

func NewModelPrefsHandler(s store.Stores) *ModelPrefsHandler {
	return &ModelPrefsHandler{stores: s}
}

// GetPreferences returns the user's model preferences.
func (h *ModelPrefsHandler) GetPreferences(c *gin.Context) {
	userID := getUserID(c)

	prefs, err := h.stores.UserSettings.GetForUser(c.Request.Context(), userID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to get preferences"})
		return
	}

	if prefs == nil {
		prefs = []models.UserModelSetting{}
	}

	c.JSON(http.StatusOK, gin.H{"data": prefs})
}

// SetPreference upserts a single model preference.
func (h *ModelPrefsHandler) SetPreference(c *gin.Context) {
	userID := getUserID(c)

	var req struct {
		ModelID              string   `json:"model_id" binding:"required"`
		ProviderConfigID     string   `json:"provider_config_id" binding:"required"`
		Hidden               *bool    `json:"hidden,omitempty"`
		PreferredTemperature *float64 `json:"preferred_temperature,omitempty"`
		PreferredMaxTokens   *int     `json:"preferred_max_tokens,omitempty"`
		SortOrder            *int     `json:"sort_order,omitempty"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	pcid := req.ProviderConfigID
	patch := models.UserModelSettingPatch{
		ProviderConfigID:     &pcid,
		Hidden:               req.Hidden,
		PreferredTemperature: req.PreferredTemperature,
		PreferredMaxTokens:   req.PreferredMaxTokens,
		SortOrder:            req.SortOrder,
	}

	if err := h.stores.UserSettings.Set(c.Request.Context(), userID, req.ModelID, &pcid, patch); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to set preference"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "preference updated"})
}

// BulkSetPreferences sets hidden state for multiple model+provider pairs at once.
func (h *ModelPrefsHandler) BulkSetPreferences(c *gin.Context) {
	userID := getUserID(c)

	var req struct {
		Entries []models.HiddenEntry `json:"entries" binding:"required"`
		Hidden  bool                 `json:"hidden"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err := h.stores.UserSettings.BulkSetHidden(c.Request.Context(), userID, req.Entries, req.Hidden); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to bulk update"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "preferences updated", "count": len(req.Entries)})
}
