package mail

import (
	"errors"
	"net/http"
	"strings"

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

func (h *Handler) DiscoverAccountConfig(w http.ResponseWriter, r *http.Request) {
	email := strings.TrimSpace(r.URL.Query().Get("email"))
	if d := validateEmailField("email", email); d != nil {
		apivalidate.WriteValidationError(w, r, apivalidate.NewValidationError(*d))
		return
	}

	result, err := autoconfig.Discover(r.Context(), email)
	if err != nil {
		if errors.Is(err, autoconfig.ErrInvalidEmail) {
			apivalidate.WriteValidationError(w, r, apivalidate.NewValidationError(
				apivalidate.FieldDetail{Field: "email", Message: "invalid"},
			))
			return
		}
		h.logger.Error("discover account config", "error", err, "email", email)
		apivalidate.WriteInternal(w, r)
		return
	}

	apiresponse.WriteJSON(w, http.StatusOK, result)
}
