// redux/slices/messagesSlice.ts
import { createSlice } from "@reduxjs/toolkit";
import { getMessagesThunk } from "../thunks/getMessagesThunk";

type Meldung = {
  t: string;
  s: number;
  c: string;
  m: string;
  i: string;
  v: string;
};

interface MessagesState {
  data: Meldung[];
  loading: boolean;
  error: string | null;
}

const initialState: MessagesState = {
  data: [],
  loading: false,
  error: null,
};

const messagesSlice = createSlice({
  name: "messages",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(getMessagesThunk.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(getMessagesThunk.fulfilled, (state, action) => {
        state.loading = false;
        state.data = action.payload;
      })
      .addCase(getMessagesThunk.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message ?? "Unbekannter Fehler";
      });
  },
});

export default messagesSlice.reducer;
