// codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/interface/http/auth/recovery_initiate.go
package auth

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

	"go.uber.org/zap"

	svc_auth "codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/service/auth"
	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/pkg/httperror"
)

type RecoveryInitiateHandler struct {
	logger  *zap.Logger
	service svc_auth.RecoveryInitiateService
}

func NewRecoveryInitiateHandler(
	logger *zap.Logger,
	service svc_auth.RecoveryInitiateService,
) *RecoveryInitiateHandler {
	return &RecoveryInitiateHandler{
		logger:  logger.Named("RecoveryInitiateHandler"),
		service: service,
	}
}

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

	var req svc_auth.RecoveryInitiateRequestDTO
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		h.logger.Error("Failed to decode recovery initiate request", zap.Error(err))
		httperror.RespondWithError(w, r, httperror.NewForBadRequestWithSingleField("payload", "Invalid request payload"))
		return
	}

	resp, err := h.service.Execute(ctx, &req)
	if err != nil {
		h.logger.Error("Recovery initiate failed", zap.Error(err))
		httperror.RespondWithError(w, r, err)
		return
	}

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