package api

import (
	"context"
	"net/http"

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

func (S *Server) updateSettings(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	userID, err := getUserIDFromRequestPath(ctx)
	if err != nil {
		S.serveError(w, r, err)
		return
	}

	callerID := r.FormValue(lib.CallerIDKey)
	if callerID == "" {
		S.serveError(w, r, autohosterrors.BadRequest("caller_id is required"))
		return
	}

	var settingsInput lib.UpdateSettingsInput
	settingsInput.Enabled = parseBool(r.FormValue(lib.EnabledKey))
	settingsInput.TeamHost = parseBool(r.FormValue(lib.TeamHostKey))

	autohostStrategy, ok := lib.ValidAutohostStrategies[r.FormValue(lib.StrategyKey)]
	if ok {
		settingsInput.Strategy = &autohostStrategy
	}

	settingsInput.DeprioritizeVodcast = parseBool(r.FormValue(lib.DeprioritizeVodcastKey))

	newSettings, err := S.hostingLogic.UpdateSettings(ctx, callerID, userID, &settingsInput)
	if err != nil {
		S.serveError(w, r, err)
		return
	}

	S.serveJSON(w, newSettings)
}
