// codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/interface/http/auth/resend_verification.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"
)

// ResendVerificationHandler handles resending verification emails
type ResendVerificationHandler struct {
	logger  *zap.Logger
	service svc_auth.ResendVerificationService
}

// NewResendVerificationHandler creates a new resend verification handler
func NewResendVerificationHandler(
	logger *zap.Logger,
	service svc_auth.ResendVerificationService,
) *ResendVerificationHandler {
	return &ResendVerificationHandler{
		logger:  logger.Named("ResendVerificationHandler"),
		service: service,
	}
}

// ServeHTTP handles the HTTP request
func (h *ResendVerificationHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	// Decode request
	var req svc_auth.ResendVerificationRequestDTO
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		h.logger.Error("Failed to decode resend verification request", zap.Error(err))
		problem := httperror.NewBadRequestError("Invalid request payload. Expected JSON with 'email' field.").
			WithInstance(r.URL.Path).
			WithTraceID(httperror.ExtractRequestID(r))
		httperror.RespondWithProblem(w, problem)
		return
	}

	// Call service (service now handles validation and returns RFC 9457 errors)
	resp, err := h.service.Execute(ctx, &req)
	if err != nil {
		h.logger.Error("Resend verification failed", zap.Error(err))
		// Service returns RFC 9457 errors, use RespondWithError to handle them
		httperror.RespondWithError(w, r, err)
		return
	}

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