import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';

import { API, namespace } from '@QPUtils/helper';
import { showNotification } from '../notificationSlice/notificationSlice';
import { __ } from '@wordpress/i18n';
import axios from 'axios';

export const getAnalytics = createAsyncThunk(
	'quizpress/getAnalytics',
	async ( payload ) => {
		try {
			const res = await API.get( `${ namespace }analytics` );
			return res.data;
		} catch ( error ) {
			thunkAPI.dispatch(
				showNotification( {
					message: error?.response?.data?.message ?? error?.message,
					isShow: true,
					type: 'error',
				} )
			);
			return thunkAPI.rejectWithValue( {
				message: error?.response?.data?.message ?? error?.message,
			} );
		}
	}
);

const dashboardSilce = createSlice( {
	name: 'analytics',
	initialState: {
		data: {},
		attempts: [],
	},
	extraReducers: ( builder ) => {
		builder.addCase( getAnalytics.fulfilled, ( state, action ) => {
			state.isLoading = false;
			state.data = action?.payload;
		} );
	},
} );

export default dashboardSilce.reducer;
