// codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/interface/http/tag/list.go
package tag

import (
	"encoding/json"
	"net/http"

	"github.com/gocql/gocql"
	"go.uber.org/zap"

	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/config"
	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/config/constants"
	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/interface/http/middleware"
	svc_tag "codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/service/tag"
	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/pkg/httperror"
)

type ListTagsHTTPHandler struct {
	config     *config.Configuration
	logger     *zap.Logger
	service    *svc_tag.TagService
	middleware middleware.Middleware
}

func NewListTagsHTTPHandler(
	config *config.Configuration,
	logger *zap.Logger,
	service *svc_tag.TagService,
	middleware middleware.Middleware,
) *ListTagsHTTPHandler {
	logger = logger.Named("ListTagsHTTPHandler")
	return &ListTagsHTTPHandler{
		config:     config,
		logger:     logger,
		service:    service,
		middleware: middleware,
	}
}

func (*ListTagsHTTPHandler) Pattern() string {
	return "GET /api/v1/tags"
}

func (h *ListTagsHTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	h.middleware.Attach(h.Execute)(w, req)
}

func (h *ListTagsHTTPHandler) Execute(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	// Get user ID from JWT context
	userID, ok := ctx.Value(constants.SessionUserID).(gocql.UUID)
	if !ok {
		h.logger.Error("Failed to get user ID from context")
		httperror.ResponseError(w, httperror.NewUnauthorizedError("User not authenticated"))
		return
	}

	// List tags
	tags, err := h.service.ListUserTags(ctx, userID)
	if err != nil {
		h.logger.Error("Failed to list tags", zap.Error(err))
		httperror.ResponseError(w, httperror.NewInternalServerError("Failed to list tags"))
		return
	}

	// Return response
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(map[string]interface{}{
		"tags": tags,
	})
}
