import { connect, StringCodec } from "nats";
import { logger } from "./logger";

const sc = StringCodec();

let nc: any;

export async function initNats() {
  const url = process.env.NATS_URL || "nats://localhost:4222";
  nc = await connect({ servers: url });
  logger.info({ url }, "NATS connected");
}

export async function publish(subject: string, payload: unknown) {
  if (!nc) {
    await initNats();
  }
  const data = sc.encode(JSON.stringify(payload));
  nc.publish(subject, data);
}
