import { v4 } from 'uuid';

import { FeatureSessionType } from '@/logging/BaseWebUserEventProperties';
import { assignFeatureSession } from '@/logging/logWebUserEvent';

import { RootStore, Substore } from './rootStore';
import { makeAutoObservableSubstore } from './utils';

enum PageRoutes {
  CREATE_PAGE = '/create',
  ARTIST_PAGE = '/artist',
  SONG_PAGE = '/song',
  PLAYLIST_PAGE = '/playlist',
  LIBRARY_PAGE = '/me',
}

export class FeatureSessionStore implements Substore {
  lastPathname: string | null = null;
  featureSessionId: string | null = null;
  featureSessionType: FeatureSessionType | null = null;

  readonly root: RootStore;
  get apiClient() {
    return this.root.apiClient;
  }
  // DO NOT ADD INIT LOGIC IN constructor. this will run on every page! considering adding any it in the component init logic instead
  constructor(root: RootStore) {
    this.root = root;
    makeAutoObservableSubstore(this);
  }

  initializeFeatureSession = (pathname: string) => {
    if (pathname === this.lastPathname) {
      assignFeatureSession(this.featureSessionType, this.featureSessionId);
      return {
        featureSessionId: this.featureSessionId,
        featureSessionType: this.featureSessionType,
      };
    }

    this.lastPathname = pathname;
    let newSessionType = null;
    if (pathname.startsWith(PageRoutes.CREATE_PAGE)) {
      newSessionType = FeatureSessionType.Create;
    }
    // TODO: refactor edit session id from ClientLayout
    // else if (pathname.startsWith('/edit')) {
    //   currentSessionType = FeatureSessionType.Edit;
    // }

    if (newSessionType) {
      this.featureSessionId = v4();
      this.featureSessionType = newSessionType;
    } else {
      this.resetFeatureSession();
      return;
    }

    assignFeatureSession(this.featureSessionType, this.featureSessionId);

    return {
      featureSessionId: this.featureSessionId,
      featureSessionType: this.featureSessionType,
    };
  };

  resetFeatureSession = () => {
    this.featureSessionId = null;
    this.featureSessionType = null;
    this.lastPathname = null;
    assignFeatureSession(null, null);
  };

  updateLastPathname = (pathname: string) => {
    this.lastPathname = pathname;
  };

  updateFeatureSessionId = (featureSessionId: string | null) => {
    this.featureSessionId = featureSessionId;
    assignFeatureSession(this.featureSessionType, this.featureSessionId);
  };

  updateFeatureSessionType = (
    featureSessionType: FeatureSessionType | null
  ) => {
    this.featureSessionType = featureSessionType;
    assignFeatureSession(this.featureSessionType, this.featureSessionId);
  };
}
