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) callRequest(r *http.Request) http.HandlerFunc {
	var request model.CallRequest
	if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
		a.logger.Warn("Failed to decode call request payload", zap.Error(err))
		return response.BadRequest(a.logger, a.Name(), "invalid_payload", "Failed to decode call request payload")
	}
	request.Normalize()
	if err := request.Validate(); err != nil {
		a.logger.Warn("Call request validation failed", zap.Error(err))
		return response.BadPayload(a.logger, a.Name(), err)
	}
	if err := a.producer.SendMessage(snotifications.CallRequest(a.Name(), &request)); err != nil {
		a.logger.Warn("Failed to enqueue call request notification", zap.Error(err))
		return response.Internal(a.logger, a.Name(), err)
	}
	return a.acceptedQueued()
}
