package server

import (
	"context"
	"errors"
	"io"
	"time"

	"github.com/fiskerinc/cloud-services/services/gateway/services"

	"github.com/fiskerinc/cloud-services/pkg/logger"
)

func logRedisErr(err error) {
	if errors.Is(err, io.EOF) {
		logger.Warn().Err(err).Send()
	} else {
		logger.Error().Err(err).Send()
	}
}

// StartRedisQueue intiates Redis queue listener
func StartRedisQueue(ctx context.Context) {
	logger.Info().Msg("initializing redis queues")

	defer func() {
		if err := recover(); err != nil {
			logger.Error().Msgf("PanicRedis %v", err)
		}
	}()

	for {
		err := services.GetRedisQueues().Listen(ctx, services.GetConnections().SendMsgToClient)
		for err != nil {
			logRedisErr(err)
			err = services.GetRedisQueues().Restart()
			time.Sleep(time.Second * 10)
		}
	}
}

// StartRedisSubscriptions initiates Redis subscription listener
func StartRedisSubscriptions(ctx context.Context) {
	logger.Info().Msg("initializing redis subscriptions")

	defer func() {
		if err := recover(); err != nil {
			logger.Error().Msgf("PanicRedis %v", err)
		}
	}()

	for {
		err := services.GetRedisPubSub().Listen(ctx, services.GetConnections().SendMsgToClient)
		for err != nil {
			logRedisErr(err)
			err = services.GetRedisPubSub().Restart()
			time.Sleep(time.Second * 10)
		}
	}
}
