package controller

import (
	"net/http"

	"github.com/QuantumNous/new-api/model"
	"github.com/gin-gonic/gin"
)

func GetModelChannels(c *gin.Context) {
	modelName := c.Query("model")
	if modelName == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "model parameter is required",
		})
		return
	}

	userId := c.GetInt("id")
	if userId == 0 {
		c.JSON(http.StatusUnauthorized, gin.H{
			"success": false,
			"message": "unauthorized",
		})
		return
	}

	userCache, err := model.GetUserCache(userId)
	if err != nil || userCache == nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "failed to get user info",
		})
		return
	}
	userGroup := userCache.Group
	if userGroup == "" {
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "failed to get user group",
		})
		return
	}

	channels, defaultChannelId, err := model.GetModelChannelsForGroup(modelName, userGroup)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "failed to query channels",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"data": gin.H{
			"channels":           channels,
			"default_channel_id": defaultChannelId,
		},
	})
}
