package events

import (
	"github.com/nats-io/nats.go"
)

type Bus struct {
	conn *nats.Conn
}

func Connect(url string) (*Bus, error) {
	conn, err := nats.Connect(url, nats.Name("ains-microservices"))
	if err != nil {
		return nil, err
	}
	return &Bus{conn: conn}, nil
}

func (b *Bus) Publish(subject string, data []byte) error {
	return b.conn.Publish(subject, data)
}

func (b *Bus) Subscribe(subject string, handler func(data []byte)) (*nats.Subscription, error) {
	return b.conn.Subscribe(subject, func(msg *nats.Msg) {
		handler(msg.Data)
	})
}

func (b *Bus) QueueSubscribe(subject, queue string, handler func(data []byte)) (*nats.Subscription, error) {
	return b.conn.QueueSubscribe(subject, queue, func(msg *nats.Msg) {
		handler(msg.Data)
	})
}

func (b *Bus) Flush() error {
	return b.conn.Flush()
}

func (b *Bus) Close() {
	if b.conn != nil {
		_ = b.conn.Drain()
		b.conn.Close()
	}
}
