import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { MyStory, RecentStory, StoryListRes } from "../../types/StatusTypes";

interface StoryState extends StoryListRes { }

const initialState: StoryState = {
  status: true,
  message: "",
  toast: false,
  data: {
    my_stories: [],
    recent_stories: [],
    viewed_stories: [],
  },
};

const StorySlice = createSlice({
  name: "story",
  initialState,
  reducers: {
    // ✅ Update partial story response (useful for patch updates)
    updateSpecificStory(state, action: PayloadAction<Partial<StoryListRes>>) {
      return { ...state, ...action.payload };
    },

    // ✅ Replace entire story response
    updateStoryListRes(state, action: PayloadAction<StoryListRes>) {
      return action.payload;
    },

    // ✅ Update view count of a specific story
    updateStoryViewCount(state, action: PayloadAction<{ storyId: number }>) {
      const { storyId } = action.payload;

      // Helper: mark story as viewed in any story list
      const markViewed = (list: RecentStory[]) => {
        list.forEach((user) => {
          user.stories.forEach((story) => {
            if (story.story_id === storyId) {
              if (!story.views) story.views = [];
              if (story.views.length === 0) {
                // Mark as viewed (or push a simple placeholder)
                story.views.push({ viewed: true });
              }
            }
          });
        });
      };

      // Mark as viewed in both lists
      markViewed(state.data.recent_stories);
      markViewed(state.data.viewed_stories);

      // Find the user who owns this story
      const userIndex = state.data.recent_stories.findIndex((user) =>
        user.stories.some((story) => story.story_id === storyId)
      );

      if (userIndex !== -1) {
        const user = state.data.recent_stories[userIndex];

        // Check if all stories of this user are viewed
        const allViewed = user.stories.every(
          (story) => Array.isArray(story.views) && story.views.length > 0
        );

        // If all stories are viewed → move user to viewed_stories
        if (allViewed) {
          const [movedUser] = state.data.recent_stories.splice(userIndex, 1);

          const alreadyExists = state.data.viewed_stories.some(
            (u) => u.user_id === movedUser.user_id
          );

          if (!alreadyExists) {
            state.data.viewed_stories.push(movedUser);
          }
        }
      }
    }



  },
});

export default StorySlice.reducer;

export const {
  updateSpecificStory,
  updateStoryListRes,
  updateStoryViewCount,
} = StorySlice.actions;
