/**
 * articleSlice — CLAUDE.md defined slice.
 * Individual article/content detail is handled by contentDetailSlice.
 * This slice manages article listing state (e.g. category article lists).
 */
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import type { RootState } from "@/store/store";

export interface Article {
  id: number;
  title: string;
  short_description?: string;
  web_image?: string;
  landscape_img?: string;
  portrait_img?: string;
  category?: string;
  channel_name?: string;
  channel_image?: string;
  total_view: number;
  total_like: number;
  is_premium?: number;
  status: number;
  created_at: string;
  updated_at: string;
}

interface ArticleState {
  items: Article[];
  isLoading: boolean;
  error: string | null;
  currentPage: number;
  totalPages: number;
}

const initialState: ArticleState = {
  items: [],
  isLoading: false,
  error: null,
  currentPage: 1,
  totalPages: 1,
};

export const fetchArticlesByCategory = createAsyncThunk(
  "articles/fetchByCategory",
  async (
    { categorySlug, userId = 0 }: { categorySlug: string; userId?: number },
    { rejectWithValue },
  ) => {
    try {
      const { default: apiClient } = await import("@/services/api.client");
      const { API_ENDPOINTS } = await import("@/lib/constants/apiEndpoints");
      const { data } = await apiClient.post<{
        status: number;
        result: Article[];
        total_rows: number;
        total_page: number;
        current_page: number;
      }>("get_category_content", {
        category_slug: categorySlug,
        user_id: userId,
      });
      return {
        items: (data.result ?? []).filter((a) => a.status === 1),
        totalPages: data.total_page ?? 1,
        currentPage: data.current_page ?? 1,
      };
    } catch (err) {
      return rejectWithValue(
        (err as Error)?.message ?? "Failed to fetch articles.",
      );
    }
  },
);

export const articleSlice = createSlice({
  name: "articles",
  initialState,
  reducers: {
    resetArticles: (state) => {
      state.items = [];
      state.currentPage = 1;
      state.totalPages = 1;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchArticlesByCategory.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(fetchArticlesByCategory.fulfilled, (state, action) => {
        state.isLoading = false;
        state.items = action.payload.items;
        state.totalPages = action.payload.totalPages;
        state.currentPage = action.payload.currentPage;
      })
      .addCase(fetchArticlesByCategory.rejected, (state, action) => {
        state.isLoading = false;
        state.error = (action.payload as string) ?? "Something went wrong.";
      });
  },
});

export const { resetArticles } = articleSlice.actions;
export default articleSlice.reducer;

export const selectArticles       = (s: RootState) => s.articles.items;
export const selectArticlesLoading = (s: RootState) => s.articles.isLoading;
export const selectArticlesPage   = (s: RootState) => s.articles.currentPage;
