package logic

import (
	"context"

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

	"code.justin.tv/live/autohost/lib"
)

// UpdateSettings updates settings
func (T *Impl) UpdateSettings(
	ctx context.Context, callerID, userID string, settingsInput *lib.UpdateSettingsInput) (*lib.Settings, error) {

	authorized, err := T.auth.CanEditChannelSettings(ctx, callerID, userID)
	if err != nil {
		return nil, err
	}
	if !authorized {
		return nil, autohosterrors.Forbidden
	}

	updatedSettings, err := T.db.UpdateSettings(ctx, userID, settingsInput)
	if err != nil {
		return nil, err
	}

	err = T.cache.SetSettings(ctx, userID, updatedSettings)
	if err != nil {
		T.logger.Error(err)
	}

	updatedSettings = addDefaultValues(updatedSettings)

	go func() {
		if err := T.trackSettings(userID, updatedSettings); err != nil {
			T.logger.Error(err)
		}
	}()

	return updatedSettings, nil
}
