// File Path: monorepo/cloud/maplepress-backend/internal/interface/http/handler/gateway/me_handler.go
package gateway

import (
	"net/http"

	"go.uber.org/zap"

	"codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/config/constants"
	"codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/pkg/httperror"
	"codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/pkg/httpresponse"
	"codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/pkg/logger"
)

// MeHandler handles the /me endpoint for getting authenticated user profile
type MeHandler struct {
	logger *zap.Logger
}

// ProvideMeHandler creates a new MeHandler
func ProvideMeHandler(logger *zap.Logger) *MeHandler {
	return &MeHandler{
		logger: logger,
	}
}

// MeResponse represents the user profile response
type MeResponse struct {
	UserID   string `json:"user_id"`
	Email    string `json:"email"`
	Name     string `json:"name"`
	Role     string `json:"role"`
	TenantID string `json:"tenant_id"`
}

// Handle handles the HTTP request for the /me endpoint
func (h *MeHandler) Handle(w http.ResponseWriter, r *http.Request) {
	// Extract user info from context (set by JWT middleware)
	userUUID, ok := r.Context().Value(constants.SessionUserUUID).(string)
	if !ok || userUUID == "" {
		h.logger.Error("user UUID not found in context")
		httperror.ProblemUnauthorized(w, "Authentication required")
		return
	}

	userEmail, _ := r.Context().Value(constants.SessionUserEmail).(string)
	userName, _ := r.Context().Value(constants.SessionUserName).(string)
	userRole, _ := r.Context().Value(constants.SessionUserRole).(string)
	tenantUUID, _ := r.Context().Value(constants.SessionTenantID).(string)

	// CWE-532: Use redacted email for logging
	h.logger.Info("/me endpoint accessed",
		zap.String("user_id", userUUID),
		logger.EmailHash(userEmail),
		logger.SafeEmail("email_redacted", userEmail))

	// Create response
	response := MeResponse{
		UserID:   userUUID,
		Email:    userEmail,
		Name:     userName,
		Role:     userRole,
		TenantID: tenantUUID,
	}

	// Write response with pretty JSON
	httpresponse.OK(w, response)
}
