package api

import (
	"context"
	"net/http"

	autohosterrors "code.justin.tv/live/autohost/internal/errors"
	"code.justin.tv/live/autohost/lib"
)

func (s *Server) hostTarget(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	channelID := r.FormValue("channel_id")
	targetID := r.FormValue("target_id")
	userID := r.FormValue("user_id")

	err := validateUserIDs(map[string]string{
		"channel_id": channelID,
		"target_id":  targetID,
		"user_id":    userID,
	})
	if err != nil {
		s.serveError(w, r, err)
		return
	}

	err = s.hostingLogic.HostTarget(ctx, userID, channelID, targetID)

	if err != nil {
		// We use an twitchhttp.Error here since it will be ignored by our Hystrix
		// middleware. Errors from TMI are numerous and Hystrix will start throttling
		// our outgoing requests if we let it handle these errors.
		twitchHTTPErr := autohosterrors.GetTwitchHTTPErr(err)
		if twitchHTTPErr != nil {
			if s.errorLogger != nil {
				s.errorLogger.RequestError(r, err)
			}

			s.serve(w, twitchHTTPErr, twitchHTTPErr.StatusCode)
			return
		}

		s.serveError(w, r, err)
		return
	}

	s.serveJSON(w, lib.Host{
		ChannelID: channelID,
		TargetID:  targetID,
	})
}
