import { QueryStreamController } from '~/core/liveCollection/QueryStreamController';
import { pullFromCache, pushToCache } from '~/cache/api';
import { ingestInCache } from '~/cache/api/ingestInCache';
import { getResolver } from '~/core/model';
import { getActiveClient } from '~/client/api/activeClient';
import { EnumJoinRequestAction } from './enum';

export class JoinRequestsQueryStreamController extends QueryStreamController<
  Amity.CommunityJoinRequestPayload,
  Amity.JoinRequestLiveCollection
> {
  private notifyChange: (params: Amity.LiveCollectionNotifyParams) => void;

  private preparePayload: (
    response: Amity.CommunityJoinRequestPayload,
  ) => Amity.ProcessedJoinRequestPayload;

  constructor(
    query: Amity.JoinRequestLiveCollection,
    cacheKey: string[],
    notifyChange: (params: Amity.LiveCollectionNotifyParams) => void,
    preparePayload: (
      response: Amity.CommunityJoinRequestPayload,
    ) => Amity.ProcessedJoinRequestPayload,
  ) {
    super(query, cacheKey);
    this.notifyChange = notifyChange;
    this.preparePayload = preparePayload;
  }

  async saveToMainDB(response: Amity.CommunityJoinRequestPayload) {
    const processedPayload = await this.preparePayload(response);

    const client = getActiveClient();
    const cachedAt = client.cache && Date.now();

    if (client.cache) {
      ingestInCache(processedPayload, { cachedAt });
    }
  }

  appendToQueryStream(
    response: Amity.CommunityJoinRequestPayload & Partial<Amity.Pagination>,
    direction: Amity.LiveCollectionPageDirection,
    refresh = false,
  ) {
    if (refresh) {
      pushToCache(this.cacheKey, {
        data: response.joinRequests.map(joinRequest =>
          getResolver('joinRequest')({ joinRequestId: joinRequest._id }),
        ),
      });
    } else {
      const collection = pullFromCache<Amity.JoinRequestLiveCollectionCache>(this.cacheKey)?.data;

      const joinRequests = collection?.data ?? [];

      pushToCache(this.cacheKey, {
        ...collection,
        data: [
          ...new Set([
            ...joinRequests,
            ...response.joinRequests.map(joinRequest =>
              getResolver('joinRequest')({ joinRequestId: joinRequest._id }),
            ),
          ]),
        ],
      });
    }
  }

  reactor(action: EnumJoinRequestAction) {
    return (joinRequest: Amity.InternalJoinRequest[]) => {
      const collection = pullFromCache<Amity.JoinRequestLiveCollectionCache>(this.cacheKey)?.data;
      if (!collection) return;

      if (action === EnumJoinRequestAction.OnLocalJoinRequestUpdated) {
        const isExist = collection.data.find(id => id === joinRequest[0].joinRequestId);
        if (!isExist) return;
      }

      if (action === EnumJoinRequestAction.OnLocalJoinRequestCreated) {
        collection.data = [
          ...new Set([
            ...joinRequest.map(joinRequest => joinRequest.joinRequestId),
            ...collection.data,
          ]),
        ];
      }

      if (action === EnumJoinRequestAction.OnLocalJoinRequestDeleted) {
        collection.data = collection.data.filter(id => id !== joinRequest[0].joinRequestId);
      }

      pushToCache(this.cacheKey, collection);
      this.notifyChange({ origin: Amity.LiveDataOrigin.EVENT, loading: false });
    };
  }

  subscribeRTE(
    createSubscriber: {
      fn: (reactor: Amity.Listener<Amity.InternalJoinRequest[]>) => Amity.Unsubscriber;
      action: EnumJoinRequestAction;
    }[],
  ) {
    return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
  }
}
