import {
  identify as amplitudeIdentify,
  getUserId,
  Identify,
  init,
  reset,
  setUserId,
  track,
} from '@amplitude/analytics-browser';

import { UserProperties } from 'src/types/amplitude';
import { type MeInstance } from 'src/types/instance';
import { type MeUser } from 'src/types/user';
import {
  type AnalyticsThemeMode,
  readPreferredAnalyticsMode,
} from 'src/utils/themeMode';

const apiKey = import.meta.env.VITE_AMPLITUDE_API_KEY;

export const initAmplitude = () => {
  if (apiKey) {
    init(import.meta.env.VITE_AMPLITUDE_API_KEY, undefined, {
      defaultTracking: false,
      minIdLength: 1,
      identityStorage: 'localStorage',
    });
  }
};

export const setUser = async (user: MeUser, instance: MeInstance) => {
  if (apiKey) {
    setUserId(String(user.id));

    const identify = new Identify();
    identify
      .set(UserProperties.INSTANCE_ID, instance.id)
      .set(UserProperties.INSTANCE_NAME, instance.name)
      .set(UserProperties.USERNAME, user.employeeInternalId)
      // Local, per-device theme preference read from storage on every init.
      .set(UserProperties.PREFERRED_MODE, readPreferredAnalyticsMode());
    await amplitudeIdentify(identify).promise;
  }
};

/** Updates the per-device theme preference (on save in Preferences/modal). */
export const setPreferredMode = (mode: AnalyticsThemeMode) => {
  if (apiKey) {
    const identify = new Identify();
    identify.set(UserProperties.PREFERRED_MODE, mode);
    void amplitudeIdentify(identify).promise;
  }
};

export const clearUser = () => {
  if (apiKey) {
    reset();
  }
};

export const logEvent = (
  eventName: string,
  eventProperties: Record<string, unknown>,
) => {
  if (apiKey && getUserId()) {
    track(eventName, {
      origin: 'WEB',
      ...eventProperties,
    });
  }
};
