import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import {
	API,
	handleSliceError,
	handleSliceSuccess,
	namespace,
} from '@QPUtils/helper';
import { __ } from '@wordpress/i18n';

export const createAnswer = createAsyncThunk(
	'quizpress/createAnswer',
	async ( formData, thunkAPI ) => {
		return await API.post( namespace + 'answers', formData )
			.then( ( res ) => {
				if ( res.status === 200 ) {
					handleSliceSuccess( thunkAPI, res.data.message );
					return res.data;
				}
			} )
			.catch( ( err ) => {
				return handleSliceError( thunkAPI, err );
			} );
	}
);

export const updateAnswer = createAsyncThunk(
	'quizpress/updateAnswer',
	async ( formData, thunkAPI ) => {
		return await API.post(
			namespace + `answers/${ formData?.answer_id }`,
			formData
		)
			.then( ( res ) => {
				if ( res.status === 200 ) {
					handleSliceSuccess( thunkAPI, res.data.message );
					return res.data;
				}
			} )
			.catch( ( err ) => {
				return handleSliceError( thunkAPI, err );
			} );
	}
);

export const fetchAnswers = createAsyncThunk(
	'quizpress/fetchAnswers',
	async ( { page = 1, per_page = 10, search = '' }, thunkAPI ) => {
		return await API.get( namespace + 'answers', {
			params: { page, per_page, search },
		} )
			.then( ( res ) => {
				if ( res.status === 200 ) {
					return res.data;
				}
			} )
			.catch( ( err ) => {
				return handleSliceError( thunkAPI, err );
			} );
	}
);

export const fetchAnswerById = createAsyncThunk(
	'quizpress/fetchAnswerById',
	async ( id, thunkAPI ) => {
		return await API.get( namespace + `answers/${ id }` )
			.then( ( res ) => {
				if ( res.status === 200 ) {
					return res.data;
				}
			} )
			.catch( ( err ) => {
				return handleSliceError( thunkAPI, err );
			} );
	}
);

export const fetchAnswerByQuestionId = createAsyncThunk(
	'quizpress/fetchAnswerByQuestionId',
	async ( id, thunkAPI ) => {
		return await API.get( namespace + `answers/${ id }` )
			.then( ( res ) => {
				if ( res.status === 200 ) {
					return res.data;
				}
			} )
			.catch( ( err ) => {
				return handleSliceError( thunkAPI, err );
			} );
	}
);

export const deleteAnswer = createAsyncThunk(
	'quizpress/deleteAnswer',
	async ( id, thunkAPI ) => {
		return await API.delete(
			namespace + `answers/${ id }`,
			{ force: true },
			{
				headers: {
					'X-HTTP-Method-Override': 'DELETE',
				},
			}
		)
			.then( ( res ) => {
				if ( res.status === 200 ) {
					handleSliceSuccess(
						thunkAPI,
						res.data.message ||
							__( 'Answers  Deleted successfully!', 'quizpress' )
					);
					return id;
				}
			} )
			.catch( ( err ) => {
				return handleSliceError( thunkAPI, err );
			} );
	}
);
