import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { sendRpcRequest } from "../../services/apiClient";
import type { INews } from "../../types/news.types";

interface INewsState {
  news: INews[];
  isNewsLoading: boolean;
  newsError: string | null;
}

const initialState: INewsState = {
  news: [],
  isNewsLoading: false,
  newsError: null,
};

export const fetchAllNews = createAsyncThunk(
  "news/fetchAllNews",
  async (_, { rejectWithValue }) => {
    try {
      const response = await sendRpcRequest<{ list: INews[] }>("news.getAll");

      return response.list;
    } catch (error: unknown) {
      if (typeof error === "object" && error !== null && "message" in error) {
        return rejectWithValue(error.message);
      }

      return rejectWithValue("Unknown error occurred");
    }
  }
);

const newsSlice = createSlice({
  name: "news",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchAllNews.pending, (state) => {
        state.isNewsLoading = true;
      })
      .addCase(fetchAllNews.fulfilled, (state, action) => {
        state.isNewsLoading = false;
        state.news = action.payload;
        state.newsError = null;
      })
      .addCase(fetchAllNews.rejected, (state, action) => {
        state.isNewsLoading = false;
        state.newsError = action.payload as string;
      });
  },
});

export default newsSlice.reducer;
