import { newId } from '@rareindex/shared'; import { events } from '@rareindex/database'; import { db } from './db.ts'; export type EventType = | 'page_discovered' | 'page_crawled' | 'listing_created' | 'listing_updated' | 'sale_detected' | 'entity_matched' | 'entity_created' | 'valuation_updated' | 'index_updated' | 'connector_run_finished' | 'radar_finding'; /** Append domain events (ยง140). Buffered per call site; flush in batches to keep inserts cheap. */ export async function emit(type: EventType, entity: { type?: string; id?: string } = {}, payload: Record = {}): Promise { await db().insert(events).values({ id: newId('event'), type, entityType: entity.type ?? null, entityId: entity.id ?? null, payload }); } export async function emitMany(rows: Array<{ type: EventType; entityType?: string; entityId?: string; payload?: Record }>): Promise { if (rows.length === 0) return; for (let i = 0; i < rows.length; i += 500) { await db() .insert(events) .values(rows.slice(i, i + 500).map((r) => ({ id: newId('event'), type: r.type, entityType: r.entityType ?? null, entityId: r.entityId ?? null, payload: r.payload ?? {} }))); } }