import { runInAction } from 'mobx';

import { components } from '@/lib/gen';

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

export type SearchTypeEnum = components['schemas']['SearchTypeEnum'];
export type SearchResult = components['schemas']['BaseSearchResult'];
export type SearchRankingEnum = components['schemas']['SearchRankingEnum'];
export type FollowingFeedItemSchema =
  components['schemas']['FollowingFeedItemSchema'];
export class SocialStore implements Substore {
  followingFeedPublishSongClips: any[] = [];
  readonly root: RootStore;
  startFeedTimestamp: string | null = null;
  lastClipTimestamp: string | null = null;
  finishedFetchingClips: boolean = false;
  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);
  }

  fetchFollowingFeedPublishSongClips = async ({
    pageSize,
  }: {
    pageSize: number;
  }) => {
    if (this.finishedFetchingClips) {
      return this.followingFeedPublishSongClips;
    }
    const { data } = await this.apiClient.POST('/api/social/following-feed/', {
      body: {
        start_feed_timestamp: this.lastClipTimestamp,
        page_size: pageSize,
        ranking_method: 'chronological',
        result_type: 'published_songs',
      },
    });
    if (!data || !data.items || data.items.length === 0) {
      this.finishedFetchingClips = true;
      return this.followingFeedPublishSongClips;
    }
    runInAction(() => {
      const publishSongClips = data.items
        ?.filter((item) => item.activity_type === 'publish_song')
        ?.map((item) => item.clip_schema);
      this.followingFeedPublishSongClips =
        this.followingFeedPublishSongClips.concat(publishSongClips ?? []);
      this.root.clips.updateClips(this.followingFeedPublishSongClips);
      this.lastClipTimestamp = data.last_item_timestamp;
    });
    return this.followingFeedPublishSongClips;
  };
}
