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 JoinRequestListQueryStreamController extends QueryStreamController<
  Amity.CommunityJoinRequestPayload,
  Amity.JoinRequestListLiveCollection
> {
  private notifyChange: (params: Amity.LiveCollectionNotifyParams) => void;

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

  constructor(
    query: Amity.JoinRequestListLiveCollection,
    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.JoinRequestListLiveCollectionCache>(
        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[] | Amity.InternalJoinRequest) => {
      const collection = pullFromCache<Amity.JoinRequestListLiveCollectionCache>(
        this.cacheKey,
      )?.data;
      if (!collection) return;

      const isArrayJoinRequest = Array.isArray(joinRequest);

      const joinRequestIds = (isArrayJoinRequest ? joinRequest : [joinRequest]).map(
        jr => jr.joinRequestId,
      );

      if (action === EnumJoinRequestAction.OnLocalJoinRequestUpdated) {
        const isExist = collection.data.find(id => joinRequestIds.includes(id));

        if (!isExist) return;
      }

      if (action === EnumJoinRequestAction.OnLocalJoinRequestCreated) {
        collection.data = [...new Set([...joinRequestIds, ...collection.data])];
      }

      if (action === EnumJoinRequestAction.OnLocalJoinRequestDeleted) {
        collection.data = collection.data.filter(id => !joinRequestIds.includes(id));
      }

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

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