import { eventBus } from '../bus';
import type { FactoryEvent } from '../types';
import { db } from '../../db/index';
import { auditLog } from '../../db/schema';

/**
 * Audit Writer Consumer
 * Writes all events to the immutable audit log
 */
export function startAuditWriter(): void {
  eventBus.on('*', async (event: FactoryEvent) => {
    try {
      // Extract entity info from event data
      const data = event.data as any;
      const entityType = event.type.split('.')[0]; // e.g., 'pipeline' from 'pipeline.created'
      const entityId = data.pipelineId || data.taskId || data.approvalId || data.agentId || 'unknown';

      await db.insert(auditLog).values({
        actorType: event.actor?.type || 'system',
        actorId: event.actor?.id,
        actorName: event.actor?.name,
        action: event.type,
        entityType,
        entityId,
        changes: data,
        metadata: { source: 'event-bus', eventId: event.id },
      });
    } catch (err) {
      // Audit should never crash the system
      console.error('[Consumer:Audit] Write failed:', err);
    }
  });

  console.log('[Consumer:Audit] Writer started');
}
