// codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/interface/http/auth/recovery_verify.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 RecoveryVerifyHandler struct {
	logger  *zap.Logger
	service svc_auth.RecoveryVerifyService
}

func NewRecoveryVerifyHandler(
	logger *zap.Logger,
	service svc_auth.RecoveryVerifyService,
) *RecoveryVerifyHandler {
	return &RecoveryVerifyHandler{
		logger:  logger.Named("RecoveryVerifyHandler"),
		service: service,
	}
}

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

	var req svc_auth.RecoveryVerifyRequestDTO
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		h.logger.Error("Failed to decode recovery verify 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 verify 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)
}
