import { createSlice } from "@reduxjs/toolkit";
import {createDB, getDBStatus} from "../httpServices/httpServiceDb";

const initialState = {
    database:[],
    dbLoading: true,
    dbError: null
}

const dbSlice = createSlice({
    name: "database",
    initialState,
    reducers:{
        setDbLoadingTrue: (state, action) => {
            state.database = []
            state.dbLoading = true
            state.dbError = null
        }
    },
    extraReducers:(builder)=>{
        // Get Database Status
        builder.addCase(getDBStatus.pending, (state) => {
            state.dbLoading = true;
            state.dbError = null;
        })
        builder.addCase(getDBStatus.fulfilled, (state, action) => {
            state.dbLoading = false;
            state.database = action.payload;
        })
        builder.addCase(getDBStatus.rejected, (state, action) => {
            state.dbLoading = false;
            state.dbError = action.payload;
        });


        // Create Database
        builder.addCase(createDB.pending, (state) => {
            state.dbLoading = true;
            state.dbError = null;
        })
        builder.addCase(createDB.fulfilled, (state, action) => {
            state.dbLoading = false;
            state.database = action.payload;
        })
        builder.addCase(createDB.rejected, (state, action) => {
            state.dbLoading = false;
            state.dbError = action.payload;
        });
    }
})

export const { setDbLoadingTrue } = dbSlice.actions;
export default dbSlice.reducer;