// Package mq owns shared RocketMQ lifecycle helpers.
package mq

import (
	"context"
	"log/slog"

	"hyapp/pkg/logx"
	"hyapp/pkg/rocketmqx"
)

// StartConsumers starts consumers in order; if one fails, already-started consumers are shut down.
func StartConsumers(consumers []*rocketmqx.Consumer) error {
	started := make([]*rocketmqx.Consumer, 0, len(consumers))
	for _, consumer := range consumers {
		if consumer == nil {
			continue
		}
		if err := consumer.Start(); err != nil {
			ShutdownConsumers(started)
			return err
		}
		started = append(started, consumer)
	}
	return nil
}

// ShutdownConsumers releases consumer groups and logs shutdown failures without masking the caller's main error.
func ShutdownConsumers(consumers []*rocketmqx.Consumer) {
	for _, consumer := range consumers {
		if consumer == nil {
			continue
		}
		if err := consumer.Shutdown(); err != nil {
			logx.Warn(context.Background(), "rocketmq_consumer_shutdown_failed", slog.String("error", err.Error()))
		}
	}
}

// StartProducers starts producers in order; if one fails, already-started producers are shut down.
func StartProducers(producers []*rocketmqx.Producer) error {
	started := make([]*rocketmqx.Producer, 0, len(producers))
	for _, producer := range producers {
		if producer == nil {
			continue
		}
		if err := producer.Start(); err != nil {
			ShutdownProducers(started)
			return err
		}
		started = append(started, producer)
	}
	return nil
}

// ShutdownProducers releases producer groups and logs shutdown failures without masking the caller's main error.
func ShutdownProducers(producers []*rocketmqx.Producer) {
	for _, producer := range producers {
		if producer == nil {
			continue
		}
		if err := producer.Shutdown(); err != nil {
			logx.Warn(context.Background(), "rocketmq_producer_shutdown_failed", slog.String("error", err.Error()))
		}
	}
}
