import { withStore } from '../../../services/AxiosInstance'

import { SubscriptionCodeOperationTypes} from './subscription-codes.action.types'
import {METADATA_END_POINTS} from '../../helpers/action-urls'
import {MettaSvr_Common} from '../../helpers/action-enums'


const postSubscriptionGenerateStart = () => ({
    type: SubscriptionCodeOperationTypes.POST_SUBSCRIPTION_CODE_START
})


const postSubscriptionGenerateSuccess = response => ({
    type: SubscriptionCodeOperationTypes.POST_SUBSCRIPTION_CODE_SUCCESS,
    payload: response
})

const postSubscriptionGenerateFailure = err => ({
    type: SubscriptionCodeOperationTypes.POST_SUBSCRIPTION_CODE_FAILURE,
    payload: err
})

export const clearPostSubscriptionGenerateState = () => ({
    type: SubscriptionCodeOperationTypes.SUBSCRIPTION_CODE_RESET_STATE
})


export const generateSubscriptionCodeAsync = (body) => {
    return async (dispatch, getState) => {
        dispatch(postSubscriptionGenerateStart())
        try{


            const {user} = getState()
            const {API_VERSION_V1, GENERATE_SUBS_CODE} = METADATA_END_POINTS.auth
            
            const response = await withStore(user.currentUser.accessToken, dispatch).getService.post(`${API_VERSION_V1}${GENERATE_SUBS_CODE}`,{createdBy: user.currentUser.userId,...body})
            const {apiResponseStatus, errorMessage, title, result } = response.data
            if (apiResponseStatus === MettaSvr_Common.APIResponseStatus.Error){
                dispatch(postSubscriptionGenerateFailure({message: errorMessage ?? title, apiResponseStatus}))
            }else{
                dispatch(postSubscriptionGenerateSuccess(result))
            }
        }catch(ex){            
            console.log("Error is: ", !!ex.response ? ex.response.data.errors : 'none')
            dispatch(postSubscriptionGenerateFailure({message: ex.message ?? ex.response.data.title, apiResponseStatus: -1}))

        }
    }
}
