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

func NewRequestOTTHandler(
	logger *zap.Logger,
	service svc_auth.RequestOTTService,
) *RequestOTTHandler {
	return &RequestOTTHandler{
		logger:  logger.Named("RequestOTTHandler"),
		service: service,
	}
}

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

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

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

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