import { Injectable } from "@nestjs/common";
import { createId } from "@paralleldrive/cuid2";
import type { MySql2Database } from "drizzle-orm/mysql2";
import { outboxRepository } from "./outbox.repository.js";
import { getTopicForEvent, buildEventPayload } from "./events.js";

@Injectable()
export class OutboxService {
  async publish(
    eventType: string,
    aggregateType: string,
    aggregateId: string,
    data: Record<string, unknown>,
    tx?: MySql2Database,
  ): Promise<string> {
    const eventId = createId();
    const topic = getTopicForEvent(eventType);
    const payload = buildEventPayload(eventType, aggregateId, data);

    await outboxRepository.create(
      {
        id: eventId,
        aggregateType,
        aggregateId,
        eventType,
        topic,
        payload: JSON.stringify(payload),
        status: "pending",
      },
      tx,
    );

    return eventId;
  }
}
