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

let producer: Producer | null = null;

export function getKafkaProducer(): Producer {
  if (!producer) {
    const kafka = new Kafka({
      clientId: env.KAFKA_CLIENT_ID,
      brokers: env.KAFKA_BROKERS.split(","),
    });
    producer = kafka.producer({
      idempotent: true,
      transactionalId: "iam-tx",
    });
  }
  return producer;
}

export async function connectKafkaProducer(): Promise<void> {
  const p = getKafkaProducer();
  await p.connect();
}

export async function disconnectKafkaProducer(): Promise<void> {
  if (producer) {
    await producer.disconnect();
    producer = null;
  }
}

/**
 * IAM Kafka topic 路由（coord-final-decisions I5 + iam_contract §1.4）。
 *
 * 事件命名规则：`<Aggregate>.<Action>`
 * - UserEvent: created/updated/disabled/role_changed
 * - RoleEvent: created/updated
 * - AuditEvent: create/update/delete/login/logout/permission_change
 */
export const IAM_KAFKA_TOPICS = {
  USER_EVENTS: "edu.iam.user.events",
  ROLE_EVENTS: "edu.iam.role.events",
  AUDIT_CREATED: "edu.iam.audit.created",
} as const;
