import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axiosInstanceClient from "@/utils/axiosClient";

interface CrudState {
  mainLoader: boolean;
  allSettings: {
    instagram: string;
    facebook: string;
    twitter: string;
    whatsapp: string;
    phone: string;
    email: string;
    location: string;
  } | null;
  error: { status: number | null };
}

const initialState: CrudState = {
  mainLoader: true,
  allSettings: null,
  error: { status: null },
};

export const getAllSettings = createAsyncThunk(
  "settings/getAllSettings",
  async (_, { rejectWithValue }) => {
    try {
      const { data } = await axiosInstanceClient.get(
        `guest/settings?paginate=0`,
      );
      return data?.data || [];
    } catch (error: any) {
      return rejectWithValue({ status: error.response?.status || 404 });
    }
  },
);

// Slice
const settingsSlice = createSlice({
  name: "settings",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(getAllSettings.pending, (state) => {
        state.mainLoader = true;
      })
      .addCase(getAllSettings.fulfilled, (state, action) => {
        state.mainLoader = false;
        const setting =
          action.payload?.length > 0 &&
          action.payload?.reduce((acc: any, item: any) => {
            acc[item.key] = item.value;
            return acc;
          }, {});
        state.allSettings = setting;
      })
      .addCase(getAllSettings.rejected, (state: any, action) => {
        state.mainLoader = false;
        state.error = action.payload;
      });
  },
});

export default settingsSlice.reducer;
