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

func NewRefreshTokenHandler(
	logger *zap.Logger,
	service svc_auth.RefreshTokenService,
) *RefreshTokenHandler {
	return &RefreshTokenHandler{
		logger:  logger.Named("RefreshTokenHandler"),
		service: service,
	}
}

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

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