import {createSlice} from "@reduxjs/toolkit";
import {createSchema, schemaStatus} from "../httpServices/httpServiceSchema";

const initialState = {
    schema: {},
    loading: true,
    error: null,
}

const schemaSlice = createSlice({
    name: "schema",
    initialState,
    reducers:{
        setSchemaLoadingTrue: (state, action) => {
            state.schema = {}
            state.loading = true
            state.error = null
        }
    },
    extraReducers:(builder)=>{
        // Get Schema Status
        builder.addCase(schemaStatus.pending, (state, action) => {
            state.loading   = true;
            state.error     = null;
        });
        builder.addCase(schemaStatus.fulfilled, (state, action) => {
            state.loading   = false;
            state.schema  = action.payload;
        });
        builder.addCase(schemaStatus.rejected, (state,action) => {
            state.loading   = false;
            state.error     = action.payload;
        });

        // Create WP Schema If not exist
        builder.addCase(createSchema.pending, (state, action) => {
            state.loading   = true;
            state.error     = null;
        });
        builder.addCase(createSchema.fulfilled, (state, action) => {
            state.loading   = false;
            state.schema    = action.payload;
        });
        builder.addCase(createSchema.rejected, (state,action) => {
            state.loading   = false;
            state.error     = action.payload;
        });
    }
})

export const { setSchemaLoadingTrue } = schemaSlice.actions;
export default schemaSlice.reducer;