package logic

import (
	"context"

	"code.justin.tv/creator-collab/log"
)

func (T *Impl) OnUserDestroyEventReceived(ctx context.Context, userID string) error {
	T.logger.Debug("Received UserDestroy event", log.Fields{
		"userId": userID,
	})

	// Remove the given user from other channels' autohost lists.
	addedList, err := T.db.GetAddedList(ctx, userID)
	if err != nil {
		T.logger.Error(err)
	}
	for _, sourceChannel := range addedList {
		_, err = T.removeListWithoutAuth(ctx, sourceChannel.ID, []string{userID})
		if err != nil {
			T.logger.Error(err)
		}
	}

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

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

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

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

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

	// Notify PDMS client that we will delete the user data
	err = T.pdms.PromiseDeletion(ctx, userID)
	if err != nil {
		return err
	}

	return nil
}
