package siteimp

import (
	"encoding/json"
	"net/http"

	"github.com/tech/sendico/pkg/api/http/response"
	snotifications "github.com/tech/sendico/pkg/messaging/notifications/site"
	"github.com/tech/sendico/pkg/model"
	"go.uber.org/zap"
)

func (a *SiteAPI) contactRequest(r *http.Request) http.HandlerFunc {
	var request model.ContactRequest
	if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
		a.logger.Warn("Failed to decode contact request payload", zap.Error(err))
		return response.BadRequest(a.logger, a.Name(), "invalid_payload", "Failed to decode contact request payload")
	}
	request.Normalize()
	if request.Topic == "" {
		request.Topic = model.ContactRequestTopicSiteContact
	}
	if err := request.Validate(); err != nil {
		a.logger.Warn("Contact request validation failed", zap.Error(err))
		return response.BadPayload(a.logger, a.Name(), err)
	}
	if err := a.producer.SendMessage(snotifications.ContactRequest(a.Name(), &request)); err != nil {
		a.logger.Warn("Failed to enqueue contact request notification", zap.Error(err))
		return response.Internal(a.logger, a.Name(), err)
	}
	return a.acceptedQueued()
}
