import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { likedContentService } from "@/services/likedContentService";
import { ContentItem } from "@/types/content";

interface LikedContentState {
  items: ContentItem[];
  isLoading: boolean;
  isLoadingMore: boolean;
  error: string | null;
  currentPage: number;
  hasMore: boolean;
  activeContentType: number;
  totalRows: number;
}

const initialState: LikedContentState = {
  items: [], isLoading: false, isLoadingMore: false,
  error: null, currentPage: 1, hasMore: false,
  activeContentType: 1, totalRows: 0,
};

export const fetchLikedContent = createAsyncThunk(
  "liked/fetch",
  async ({ contentType, pageNo }: { contentType: number; pageNo: number }, { rejectWithValue }) => {
    try {
      const res = await likedContentService.getLikedContent(contentType, pageNo);
      if (res.status !== 200) return rejectWithValue(res.message);
      return {
        items: res.result.map(likedContentService.mapItem),
        hasMore: res.more_page,
        currentPage: res.current_page,
        contentType,
        totalRows: res.total_rows,
      };
    } catch (err: unknown) {
      return rejectWithValue(err instanceof Error ? err.message : "Failed to load liked content");
    }
  },
);

const likedContentSlice = createSlice({
  name: "liked",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchLikedContent.pending, (state, action) => {
        state.error = null;
        if (action.meta.arg.pageNo === 1) { state.isLoading = true; state.items = []; }
        else state.isLoadingMore = true;
      })
      .addCase(fetchLikedContent.fulfilled, (state, action) => {
        state.isLoading = false; state.isLoadingMore = false;
        state.hasMore = action.payload.hasMore;
        state.currentPage = action.payload.currentPage;
        state.activeContentType = action.payload.contentType;
        state.totalRows = action.payload.totalRows;
        if (action.payload.currentPage === 1) state.items = action.payload.items;
        else state.items.push(...action.payload.items);
      })
      .addCase(fetchLikedContent.rejected, (state, action) => {
        state.isLoading = false; state.isLoadingMore = false;
        state.error = action.payload as string;
      });
  },
});

export default likedContentSlice.reducer;
