import { isCoverFeatureEnabled } from '@/utils/session';

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

export class ContestStore implements Substore {
  readonly root: RootStore;
  submittedClips = new Set<string>();
  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);
  }

  // TODO: this is a temp solution to optimistically render publish button change
  handleEnterContest = ({
    isEntering,
    clipId,
  }: {
    isEntering: boolean;
    clipId: string;
  }) => {
    if (isEntering) {
      this.submittedClips.add(clipId);
    } else {
      this.submittedClips.delete(clipId);
    }
  };

  isClipSubmitted = (clipId: string) => {
    return this.submittedClips.has(clipId);
  };

  // TODO: this was just used for timbaland
  isCoverEnabledOrIsContest = async (
    clipId: string,
    clipUserID: string
  ): Promise<boolean> => {
    if (isCoverFeatureEnabled(this.root.session)) {
      return true;
    }
    if (clipUserID !== this.root.session.userId) {
      return false;
    }

    const cacheKey = `contestClip_${clipId}`;
    const cachedResult = localStorage.getItem(cacheKey);
    if (cachedResult !== null) {
      return JSON.parse(cachedResult);
    }

    const isContestClip = await this.isContestClip(clipId);
    localStorage.setItem(cacheKey, JSON.stringify(isContestClip));
    return isContestClip;
  };

  // TODO: this was just used for timbaland
  isContestClip = async (clipId: string): Promise<boolean> => {
    const { data } = await this.apiClient.GET(
      `/api/contests/is_contest_clip/{clip_id}/`,
      {
        params: {
          path: {
            clip_id: clipId,
          },
        },
      }
    );
    return !!data;
  };
}
