import { eq } from "drizzle-orm";
import { integer, jsonb, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
//#region src/outbox.ts
const outboxTable = pgTable("outbox", {
	id: uuid("id").primaryKey().defaultRandom(),
	aggregateType: text("aggregate_type").notNull(),
	aggregateId: text("aggregate_id").notNull(),
	eventType: text("event_type").notNull(),
	payload: jsonb("payload").notNull(),
	processedAt: timestamp("processed_at", { withTimezone: true }),
	failedAt: timestamp("failed_at", { withTimezone: true }),
	retryCount: integer("retry_count").notNull().default(0),
	lastError: text("last_error"),
	createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
});
const schema = { outbox: outboxTable };
async function insertOutboxRow(db, values) {
	const [row] = await db.insert(outboxTable).values(values).returning();
	if (!row) throw new Error("insertOutboxRow: insert returned no row");
	return row;
}
/** Post-commit, fire-and-forget — never throws. Sends `{ outboxId }` only. */
function enqueueOutbox(queue, outboxId) {
	queue.send({ outboxId }).catch(() => {});
}
async function dispatchOutboxRow(registry, db, row, env, opts) {
	if (row.processedAt != null) return "skipped";
	if ((await db.select({ processedAt: outboxTable.processedAt }).from(outboxTable).where(eq(outboxTable.id, row.id)).limit(1))[0]?.processedAt != null) return "skipped";
	await registry.dispatch(env, {
		type: row.eventType,
		payload: row.payload
	}, opts);
	await db.update(outboxTable).set({ processedAt: /* @__PURE__ */ new Date() }).where(eq(outboxTable.id, row.id));
	return "dispatched";
}
//#endregion
export { dispatchOutboxRow, enqueueOutbox, insertOutboxRow, schema as outboxSchema, outboxTable };
