"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _toolkit = require("@reduxjs/toolkit");
var _useCustomRankingGlobalFeed = require("../../../social/hooks/useCustomRankingGlobalFeed");
const initialState = {
  postList: [],
  paginationData: {
    next: null,
    previous: null
  }
};
const globalFeedSlice = (0, _toolkit.createSlice)({
  name: 'globalFeed',
  initialState,
  reducers: {
    setNewGlobalFeed: (state, action) => {
      const seen = new Set();
      state.postList = action.payload.filter(post => {
        if (seen.has(post.postId)) return false;
        seen.add(post.postId);
        return true;
      });
    },
    updateGlobalFeed: (state, action) => {
      const uniqueIds = new Set(state.postList.map(post => (0, _useCustomRankingGlobalFeed.isAmityAd)(post) ? post.adId : post.postId));
      const newUnique = [];
      for (const post of action.payload) {
        const id = (0, _useCustomRankingGlobalFeed.isAmityAd)(post) ? post.adId : post.postId;
        if (!uniqueIds.has(id)) {
          uniqueIds.add(id);
          newUnique.push(post);
        }
      }
      state.postList = [...state.postList, ...newUnique];
    },
    setPaginationData: (state, action) => {
      state.paginationData = action.payload;
    },
    addPostToGlobalFeed: (state, action) => {
      const alreadyExists = state.postList.some(item => !(0, _useCustomRankingGlobalFeed.isAmityAd)(item) && item.postId === action.payload.postId);
      if (!alreadyExists) {
        state.postList = [action.payload, ...state.postList];
      }
    },
    updateByPostId: (state, action) => {
      const {
        postId,
        postDetail
      } = action.payload;
      const index = state.postList.findIndex(item => !(0, _useCustomRankingGlobalFeed.isAmityAd)(item) && item.postId === postId);
      state.postList[index] = postDetail;
    },
    deleteByPostId: (state, action) => {
      const {
        postId
      } = action.payload;
      const prevPostList = [...state.postList];
      const updatedPostList = prevPostList.filter(item => !(0, _useCustomRankingGlobalFeed.isAmityAd)(item) && item.postId !== postId);
      state.postList = updatedPostList;
    },
    clearFeed: state => {
      state.postList = [];
    }
  }
});
var _default = exports.default = globalFeedSlice;
//# sourceMappingURL=globalfeedSlice.js.map