// codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/interface/http/user/publiclookup.go
package user

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

	"go.uber.org/zap"

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

type UserPublicLookupHTTPHandler struct {
	config     *config.Config
	logger     *zap.Logger
	service    svc_user.UserPublicLookupService
	middleware middleware.Middleware
}

func NewUserPublicLookupHTTPHandler(
	config *config.Config,
	logger *zap.Logger,
	service svc_user.UserPublicLookupService,
	middleware middleware.Middleware,
) *UserPublicLookupHTTPHandler {
	logger = logger.Named("UserPublicLookupHTTPHandler")
	return &UserPublicLookupHTTPHandler{
		config:     config,
		logger:     logger,
		service:    service,
		middleware: middleware,
	}
}

func (*UserPublicLookupHTTPHandler) Pattern() string {
	return "GET /iam/api/v1/users/lookup"
}

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

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

	// 🔍 DEBUG: Log the raw query string to see what's actually received
	h.logger.Debug("🔍 Raw query string", zap.String("raw_query", r.URL.RawQuery))

	// r.URL.Query().Get() already URL-decodes the parameter automatically
	email := r.URL.Query().Get("email")
	if email == "" {
		httperror.RespondWithError(w, r, httperror.NewForBadRequestWithSingleField("email", "Email parameter required"))
		return
	}

	// 🔍 DEBUG: Log what we got from Query().Get()
	h.logger.Debug("🔍 Email from Query().Get()", zap.String("email", validation.MaskEmail(email)))
	h.logger.Debug("received email", zap.String("email", validation.MaskEmail(email)))

	// Basic email validation
	if !strings.Contains(email, "@") {
		httperror.RespondWithError(w, r, httperror.NewForBadRequestWithSingleField("email", "Invalid email format"))
		return
	}

	var req svc_user.UserPublicLookupRequestDTO
	req.Email = email

	response, err := h.service.Execute(ctx, &req)
	if err != nil {
		httperror.RespondWithError(w, r, err)
		return
	}

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