package logic

import (
	"context"
	"fmt"

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

	"code.justin.tv/creator-collab/log/errors"
	"code.justin.tv/eventbus/schema/pkg/channel_endorsement_list"
)

// SetList sets a list; resets current list with new list from parameters
func (T *Impl) SetList(ctx context.Context, callerID, userID string, list []string) ([]string, error) {
	authorized, err := T.auth.CanEditChannelSettings(ctx, callerID, userID)
	if err != nil {
		return nil, err
	}
	if !authorized {
		return nil, autohosterrors.Forbidden
	}

	// Don't allow adding yourself to your autohost list
	for i, target := range list {
		if target == userID {
			list = append(list[:i], list[i+1:]...)
			break
		}
	}

	oldList, err := T.db.GetList(ctx, userID)
	if err != nil {
		return nil, err
	}

	newList, err := T.db.SetList(ctx, userID, list)
	if err != nil {
		return nil, err
	}

	// Save changes to cache
	err = T.cache.SetList(ctx, userID, newList)
	if err != nil {
		T.logger.Error(err)
	}

	if err = T.eventPublisher.ChannelEndorsementListUpdate(ctx, &channel_endorsement_list.ChannelEndorsementListUpdate{UserId: userID}); err != nil {
		T.logger.Error(errors.Wrap(err, "could not publish channel endorsement list update event", errors.Fields{"channel_id": userID}))
	}

	err = T.setListSNS.SendToTopic(ctx, setListMessage{
		ChannelID: userID,
		NewList:   newList,
	})
	if err != nil {
		verboseErr := fmt.Errorf("Error sending event (set autohost list) to sns. Error: %s", err)
		T.logger.Error(verboseErr)
	}

	addedTargets, removedTargets := listDiff(newList, oldList)
	err = T.helpers.AddedChannel(ctx, userID, addedTargets)
	if err != nil {
		T.logger.Error(err)
	}
	err = T.helpers.DeletedChannel(ctx, userID, removedTargets)
	if err != nil {
		T.logger.Error(err)
	}

	return newList, nil
}
