import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import { addons, makeRequest } from '@QPUtils/helper';
import { showNotification } from '../notificationSlice/notificationSlice';

export const fetchAddons = createAsyncThunk(
	'quizpress/fetchAddons',
	async ( thunkAPI ) => {
		try {
			return await makeRequest( 'get_all_addons' );
		} catch ( e ) {
			thunkAPI.dispatch(
				showNotification( { message: e, isShow: true, type: 'error' } )
			);
		}
	}
);

export const saveAddon = createAsyncThunk(
	'quizpress/saveAddon',
	( { addon, status }, thunkAPI ) => {
		try {
			return makeRequest( 'saved_addon_status', {
				addon_name: addon.label,
				addon_slug: addon.name,
				required_plugin: JSON.stringify( addon.required_plugin ),
				status,
			} ).then( ( res ) => {
				if ( res ) {
					return res;
				}
			} );
		} catch ( e ) {
			console.log( { e } );
			thunkAPI.dispatch(
				showNotification( {
					message: e?.response?.data?.message ?? e?.message,
					isShow: true,
					type: 'error',
				} )
			);
		}
	}
);

const addonSlice = createSlice( {
	name: 'addons',
	initialState: addons,
	extraReducers: ( builder ) => {
		builder
			.addCase(
				fetchAddons.fulfilled,
				( state, action ) => action.payload
			)
			.addCase(
				saveAddon.fulfilled,
				( state, action ) => action.payload
			);
	},
} );

export default addonSlice.reducer;
