import { emitter } from '../emitter.js';
import { createWithId } from '../../utils/id.js';
import { insert as insertActivityLog } from '../../repositories/activityLog.repo.js';

interface ActivityEventPayload {
  user_id?: string;
  entity_type: string;
  entity_id?: string;
  action: string;
  old_values?: unknown;
  new_values?: unknown;
  description?: string;
  ip_address?: string;
}

// Higher maxAttempts than createWithId's default (8) — this table takes the
// heaviest concurrent write load of anything using that helper (one row per
// stage move/dispatch/edit, from every user at once), so a burst of
// simultaneous activity easily outlasts 8 collision retries. This runs off
// the request's response path (see the catch below — a failure here is
// logged, not surfaced to whoever triggered the original action), so the
// extra attempts only cost time in the background, never in a user-facing
// response.
const ACTIVITY_LOG_MAX_ATTEMPTS = 20;

export function registerActivityLogHandler() {
  emitter.on('activity.create', async (payload: ActivityEventPayload) => {
    try {
      await createWithId('activity_logs', 'LOG', (id) => insertActivityLog({ ...payload }, id), undefined, ACTIVITY_LOG_MAX_ATTEMPTS);
    } catch (err) {
      console.error('Failed to write activity log:', err);
    }
  });
}
