import { EnviveAnalytics } from '@envive-ai/analytics';
import Logger from 'src/application/logging/logger';
import { getAtomStore } from 'src/atoms/atomStore';
import { userIdAtom } from 'src/atoms/app';
import { ExecutionContext } from '@envive-ai/analytics/dist/analytics/EnviveAnalytics';

const logger = new Logger('userIdentityService');

type UserIdentityServiceProps = {
  apiKey: string;
};

export class UserIdentityService {
  private readonly apiKey: string;

  private readonly USER_ID_OVERRIDE_KEY = 'v1-spiffy-user-id-override';

  constructor({ apiKey }: UserIdentityServiceProps) {
    this.apiKey = apiKey;
  }

  getUserIdOverrideFromLocalStorage(): string | undefined {
    logger.logDebug('Getting userID from localStorage');
    return localStorage.getItem(this.USER_ID_OVERRIDE_KEY) ?? undefined;
  }

  async getUserIdOrDefault(): Promise<string> {
    const userIdOverride = this.getUserIdOverrideFromLocalStorage();
    if (userIdOverride) {
      return userIdOverride;
    }

    try {
      logger.logDebug('Getting userID via EnviveAnalytics in UserIdentityService');
      const enviveAnalytics = new EnviveAnalytics({
        apiKey: this.apiKey,
        environmentInfo: { executionContext: ExecutionContext.EnviveReactComponentsV3 },
      });
      const enviveUserId = await enviveAnalytics.resolveEnviveUserId();

      if (!enviveUserId) {
        throw new Error('EnviveAnalytics.resolveEnviveUserId() returned null/undefined');
      }

      return enviveUserId;
    } catch (error: unknown) {
      logger.logError('CRITICAL: Failed to get user ID:', error);
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      throw new Error(`CRITICAL: User ID resolution failed: ${errorMessage}`);
    }
  }

  async initializeUser(atomStore?: ReturnType<typeof getAtomStore>): Promise<void> {
    try {
      const userId = await this.getUserIdOrDefault();

      const store = atomStore || getAtomStore();
      store.set(userIdAtom, userId);
    } catch (error) {
      logger.logError('CRITICAL: Failed to initialize user ID:', error);
      throw error;
    }
  }
}
