import { Kafka } from "kafkajs";
import { env } from "./env.js";

export const kafka = new Kafka({
  brokers: env.KAFKA_BROKERS.split(","),
  clientId: "core-edu-service",
});

export const producer = kafka.producer({
  idempotent: true,
  transactionalId: "core-edu-tx",
});

export const consumer = kafka.consumer({ groupId: "core-edu-group" });

export async function connectKafka(): Promise<void> {
  try {
    await producer.connect();
    await consumer.connect();
    console.log("Kafka connected");
  } catch (err) {
    console.warn(
      "Kafka connect failed, running without Kafka:",
      err instanceof Error ? err.message : String(err),
    );
  }
}

export async function disconnectKafka(): Promise<void> {
  await producer.disconnect();
  await consumer.disconnect();
}
