package mail

import (
	"net/http"

	"github.com/ultisuite/ulti-backend/internal/api/apiresponse"
	"github.com/ultisuite/ulti-backend/internal/api/apivalidate"
	"github.com/ultisuite/ulti-backend/internal/api/middleware"
)

func (h *Handler) GetMailSettings(w http.ResponseWriter, r *http.Request) {
	claims := middleware.ClaimsFromContext(r.Context())

	settings, err := h.svc.GetMailSettings(r.Context(), claims.Sub)
	if err != nil {
		h.logger.Error("get mail settings", "error", err)
		apivalidate.WriteInternal(w, r)
		return
	}
	apiresponse.WriteJSON(w, http.StatusOK, settings)
}

func (h *Handler) UpdateMailSettings(w http.ResponseWriter, r *http.Request) {
	claims := middleware.ClaimsFromContext(r.Context())

	var req patchMailSettingsRequest
	if err := apivalidate.DecodeJSON(w, r, maxSettingsRequestBody, &req); err != nil {
		return
	}
	if verr := validatePatchMailSettings(&req); verr != nil {
		apivalidate.WriteValidationError(w, r, verr)
		return
	}

	settings, err := h.svc.UpdateMailSettings(r.Context(), claims.Sub, &req)
	if err != nil {
		h.logger.Error("update mail settings", "error", err)
		apivalidate.WriteInternal(w, r)
		return
	}
	apiresponse.WriteJSON(w, http.StatusOK, settings)
}
