import { Api } from '@mondaydotcomorg/trident-backend-api';
import type { RawUser } from '@mondaydotcomorg/bigbrain-types';

function getUserContext(): { user_name?: string; user_email?: string } {
  const user = Api.getPart('context')?.execution.get()?.user as RawUser | undefined;
  return user ? { user_name: user.name, user_email: user.email } : {};
}

/**
 * Sends a BI event via the Trident runtime's bigbrain tracker, auto-attaching the current user.
 * No-ops (with a warning) if `Runtime.init()` hasn't run yet.
 *
 * Only exposed from the `/trident` entry, never the root: importing it loads
 * `@mondaydotcomorg/trident-backend-api`, which a standalone process (e.g. the CLI) doesn't
 * install. Those callers stay on the root entry and use `createHttpTracker` instead.
 */
export async function trackEvent(name: string, data: Record<string, unknown>, source: string): Promise<void> {
  const tracker = Api.getPart('bigbrain')?.tracker;
  if (!tracker) {
    // eslint-disable-next-line no-console
    console.warn('[z2h-shared-utils] trackEvent: bigbrain API part unavailable. Dropping event.');
    return;
  }
  // Call through `tracker`, not a destructured reference — sendBiEvent relies on `this` internally.
  tracker.sendBiEvent({ name, source, data: { ...getUserContext(), ...data } });
}
