// monorepo/cloud/backend/internal/maplefile/interface/http/collection/find_root_collections.go
package collection

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

	"go.uber.org/zap"

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

type FindRootCollectionsHTTPHandler struct {
	config     *config.Configuration
	logger     *zap.Logger
	service    svc_collection.FindRootCollectionsService
	middleware middleware.Middleware
}

func NewFindRootCollectionsHTTPHandler(
	config *config.Configuration,
	logger *zap.Logger,
	service svc_collection.FindRootCollectionsService,
	middleware middleware.Middleware,
) *FindRootCollectionsHTTPHandler {
	logger = logger.Named("FindRootCollectionsHTTPHandler")
	return &FindRootCollectionsHTTPHandler{
		config:     config,
		logger:     logger,
		service:    service,
		middleware: middleware,
	}
}

func (*FindRootCollectionsHTTPHandler) Pattern() string {
	return "GET /api/v1/collections/root"
}

func (h *FindRootCollectionsHTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// Apply middleware before handling the request
	h.middleware.Attach(h.Execute)(w, req)
}

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

	resp, err := h.service.Execute(ctx)
	if err != nil {
		h.logger.Error("Failed to find root collections", zap.Error(err))
		// Service returns RFC 9457 errors, use RespondWithError to handle them
		httperror.RespondWithError(w, r, err)
		return
	}

	if resp == nil {
		h.logger.Error("No collections returned from service")
		problem := httperror.NewInternalServerError("Failed to retrieve collections. Please try again.").
			WithInstance(r.URL.Path).
			WithTraceID(httperror.ExtractRequestID(r))
		httperror.RespondWithProblem(w, problem)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	if err := json.NewEncoder(w).Encode(resp); err != nil {
		h.logger.Error("Failed to encode collections response", zap.Error(err))
		// At this point headers are already sent, log the error but can't send RFC 9457 response
		return
	}
}
