package handler import ( "errors" "log" "net/http" "strings" "github.com/dusiburg/fancy-api/internal/model" "github.com/dusiburg/fancy-api/internal/provider/dictionary" "github.com/dusiburg/fancy-api/internal/provider/llm" "github.com/dusiburg/fancy-api/internal/service" "github.com/gin-gonic/gin" "github.com/google/uuid" ) type DictionaryHandler struct { service *service.DictionaryService } func NewDictionaryHandler(svc *service.DictionaryService) *DictionaryHandler { return &DictionaryHandler{service: svc} } func userID(c *gin.Context) (uuid.UUID, bool) { val, exists := c.Get("user_id") if !exists { return uuid.UUID{}, false } id, ok := val.(uuid.UUID) return id, ok } func (h *DictionaryHandler) Lookup(c *gin.Context) { userID, ok := userIDFromContext(c) if !ok { c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) return } word := strings.ToLower(strings.TrimSpace(c.Param("word"))) if word == "" { c.JSON(http.StatusBadRequest, gin.H{"error": "word is required"}) return } lang, ok := model.ParseLanguage(c.Param("lang")) if !ok { c.JSON(http.StatusBadRequest, gin.H{"error": "unsupported language"}) return } result, err := h.service.Lookup(c.Request.Context(), userID, word, lang) if err != nil { log.Printf("lookup %q [%s]: %v", word, lang, err) switch { case errors.Is(err, dictionary.ErrWordNotFound): c.JSON(http.StatusNotFound, gin.H{"error": "word not found"}) case errors.Is(err, dictionary.ErrUnsupportedLanguage): c.JSON(http.StatusBadRequest, gin.H{"error": "unsupported language"}) case errors.Is(err, llm.ErrQuotaExceeded): c.JSON(http.StatusTooManyRequests, gin.H{"error": "limit exceeded"}) default: c.JSON(http.StatusInternalServerError, gin.H{"error": "getting dictionary data failed"}) } return } c.JSON(http.StatusOK, result) }