package logic

import (
	"context"

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

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

// GetSettings gets settings
func (T *Impl) GetSettings(ctx context.Context, callerID, userID string) (*lib.Settings, error) {
	authorized, err := T.auth.CanEditChannelSettings(ctx, callerID, userID)
	if err != nil {
		return nil, err
	}
	if !authorized {
		return nil, autohosterrors.Forbidden
	}

	return T.getSettingsWithoutAuth(ctx, userID)
}

func (T *Impl) getSettingsWithoutAuth(ctx context.Context, userID string) (*lib.Settings, error) {
	settings, cacheHit, err := T.cache.GetSettings(ctx, userID)
	if err != nil {
		T.logger.Error(err)
	} else if cacheHit {
		settings = addDefaultValues(settings)
		return settings, nil
	}

	settings, err = T.db.GetSettings(ctx, userID)
	if err != nil {
		return nil, err
	}

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

	settings = addDefaultValues(settings)
	return settings, nil
}

func addDefaultValues(settings *lib.Settings) *lib.Settings {
	if settings == nil {
		settings = &lib.Settings{}
	}
	if settings.Strategy == "" {
		settings.Strategy = lib.AutohostStrategyRandom
	}
	if settings.CanBeRaidedBy == "" {
		settings.CanBeRaidedBy = lib.CanBeRaidedByAll
	}
	return settings
}
