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

func NewRecoveryCompleteHandler(
	logger *zap.Logger,
	service svc_auth.RecoveryCompleteService,
) *RecoveryCompleteHandler {
	return &RecoveryCompleteHandler{
		logger:  logger.Named("RecoveryCompleteHandler"),
		service: service,
	}
}

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

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