// codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/interface/http/tag/get.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/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 GetTagHTTPHandler struct {
	config     *config.Configuration
	logger     *zap.Logger
	service    *svc_tag.TagService
	middleware middleware.Middleware
}

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

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

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

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

	// Get tag ID from path
	idStr := r.PathValue("id")
	if idStr == "" {
		httperror.ResponseError(w, httperror.NewBadRequestError("Tag ID is required"))
		return
	}

	tagID, err := gocql.ParseUUID(idStr)
	if err != nil {
		h.logger.Error("Invalid tag ID", zap.Error(err), zap.String("id", idStr))
		httperror.ResponseError(w, httperror.NewBadRequestError("Invalid tag ID format"))
		return
	}

	// Get tag
	tag, err := h.service.GetTag(ctx, tagID)
	if err != nil {
		h.logger.Error("Failed to get tag", zap.Error(err), zap.String("id", idStr))
		httperror.ResponseError(w, httperror.NewNotFoundError("Tag not found"))
		return
	}

	// Return response
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(tag)
}
