import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { GET } from "../../utils/api";
import { API } from "../../endpoints/common_endpoints";

export const getblog = createAsyncThunk(
    'blog/get-blog',
    async (_, { rejectWithValue }) => {
        try {
            const blogData = await GET(API.GET_BLOG);
            return blogData;
        } catch (error) {
            return rejectWithValue(error.message);
        }
    }
);

export const getblogById = createAsyncThunk(
    'blog/get-blogbyid',
    async (id, { rejectWithValue }) => {
        try {
            const blogbyidData = await GET(API.GET_BLOG_BY_ID + `/${id}`);
            return blogbyidData;

        } catch (error) {
            return rejectWithValue(error.message);
        }
    }
);

// Create the slice
const Slice = createSlice({
    name: "blog",
    initialState: {
        name: '',
        subname: '',
        image: '',
        description: '',
        createdAt: '',
        selectedBlog: null,
        error: null,
        status: 'idle',

    },

    reducers: {
        seletedBlog: (state, action) => {
            state.selectedBlog = action.payload;

        }
    },
    extraReducers: (builder) => {
        builder

            .addCase(getblog.pending, (state) => {
                state.status = 'loading';
               
            })
            .addCase(getblog.fulfilled, (state, action) => {
                state.status = 'succeeded';
                state.blog = action.payload?.data || [];
             
            })
            .addCase(getblog.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload;
              
            })


            .addCase(getblogById.pending, (state) => {
                state.status = 'loading';
               
            })
            .addCase(getblogById.fulfilled, (state, action) => {
                state.status = 'succeeded';
                state.blog = action.payload?.data || [];
                
            })
            .addCase(getblogById.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload;
               
            })
    },
});

export default Slice.reducer;


