package v1handler

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/rose_cat707/luminary/internal/gateway"
	"github.com/rose_cat707/luminary/internal/model"
	"github.com/rose_cat707/luminary/internal/prediction"
)

type ModelsHandler struct {
	gateway   *gateway.Service
	predictions *prediction.Service
	baseURL   func() string
}

func NewModelsHandler(gw *gateway.Service, pred *prediction.Service, baseURL func() string) *ModelsHandler {
	return &ModelsHandler{gateway: gw, predictions: pred, baseURL: baseURL}
}

func (h *ModelsHandler) List(c *gin.Context) {
	ingress, ok := ingressKey(c)
	if !ok {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
		return
	}
	switch ingress.EffectiveProtocol() {
	case model.IngressProtocolImage:
		results, err := h.predictions.ListPublicModels(c.Request.Context(), ingress, h.baseURL())
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"detail": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"previous": nil,
			"next":     nil,
			"results":  results,
		})
	default:
		models, err := h.gateway.ListModels(c.Request.Context(), ingress)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"object": "list", "data": models})
	}
}

func ingressKey(c *gin.Context) (*model.IngressKey, bool) {
	v, ok := c.Get("ingress_key")
	if !ok {
		return nil, false
	}
	k, ok := v.(*model.IngressKey)
	return k, ok
}
