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

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

func (*UnassignTagHTTPHandler) Pattern() string {
	return "DELETE /api/v1/tags/{tagId}/entities/{entityId}"
}

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

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

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

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

	// Get entity ID from path
	entityIDStr := r.PathValue("entityId")
	if entityIDStr == "" {
		httperror.ResponseError(w, httperror.NewBadRequestError("Entity ID is required"))
		return
	}

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

	// Get entity type from query parameter
	entityType := r.URL.Query().Get("entity_type")
	if entityType == "" {
		httperror.ResponseError(w, httperror.NewBadRequestError("Entity type is required"))
		return
	}

	// Unassign tag
	if err := h.service.UnassignTag(ctx, tagID, entityID, entityType); err != nil {
		h.logger.Error("Failed to unassign tag",
			zap.Error(err),
			zap.String("tag_id", tagIDStr),
			zap.String("entity_id", entityIDStr),
			zap.String("entity_type", entityType),
		)
		httperror.ResponseError(w, httperror.NewInternalServerError("Failed to unassign tag"))
		return
	}

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