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

import (
	"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 DeleteTagHTTPHandler struct {
	config     *config.Configuration
	logger     *zap.Logger
	service    *svc_tag.TagService
	middleware middleware.Middleware
}

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

func (*DeleteTagHTTPHandler) Pattern() string {
	return "DELETE /api/v1/tags/{id}"
}

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

func (h *DeleteTagHTTPHandler) 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
	}

	// 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
	}

	// Delete tag
	if err := h.service.DeleteTag(ctx, userID, tagID); err != nil {
		h.logger.Error("Failed to delete tag", zap.Error(err), zap.String("id", idStr))
		httperror.ResponseError(w, httperror.NewInternalServerError("Failed to delete tag"))
		return
	}

	// Return response
	w.WriteHeader(http.StatusNoContent)
}
