import axiosClient from '@/config/axios'
import { removeToken, isApiSuccess, setToken, setRefreshToken, getRefreshToken } from '@/helper'


export const login = ({ commit }, formData) => {
  return axiosClient
    .post('login', formData)
    .then(response => {

      if (isApiSuccess(response)) {
        commit('SET_USER', response.data.user)
        commit('SET_AUTHENTICATED', false)
      }

      return Promise.resolve(response)
    }).catch(exception => {
      commit('SET_USER', {})
      commit('SET_AUTHENTICATED', false)
      console.log('Login Action Exception', exception);
    })
}

export const verifyOTP = ({ commit }, formData) => {
  return axiosClient.post('verifysms', formData)
    .then(response => {

      if (isApiSuccess(response)) {
        commit('SET_AUTHENTICATED', true)

        setToken(response.data.access_token)
        setRefreshToken(response.data.refresh_token)
      }

      return Promise.resolve(response)
    }).catch(exception => {
      console.log('verifyOTP Action Exception', exception);
    })
}

export const authenticateWithRefreshToken = ({ commit }) => {
  return axiosClient.post('refreshtoken', { refresh_token: getRefreshToken() })
    .then(response => {

      if (isApiSuccess(response)) {
        commit('SET_AUTHENTICATED', true)

        setToken(response.data.access_token)
        setRefreshToken(response.data.refresh_token)
      }

      return Promise.resolve(response)
    }).catch(exception => {
      console.log('authenticateWithRefreshToken Action Exception', exception);
    })
}

export const resendOTP = ({ commit }, formData) => {
  return axiosClient.post('resendotp', formData)
    .then(response => {
      return Promise.resolve(response)
    }).catch(exception => {
      console.log('Login Action Exception', exception);
    })
}

export const authUser = ({ commit }) => {
  return axiosClient.get('get-authinfo')
    .then(response => {
      commit('SET_AUTHENTICATED', true)
      commit('SET_USER', response.data.user)
      commit('SET_PERMISSIONS', response.data.permissions)
      return Promise.resolve(response)
    }).catch(exception => {
      console.log('Get Auth User Action Exception', exception);
    })
}

export const logout = ({ commit }) => {
  commit('SET_USER', {})
  commit('SET_AUTHENTICATED', false)
  removeToken()
}

export const setLoader = ({ commit }, status) => {
  commit('SET_LOADER', status)
}

export const loadPermissions = ({ commit }) => {
  return axiosClient
    .get('getpermission')
    .then(response => {
      commit('SET_PERMISSIONS', response.data.permissions)
      return Promise.resolve(response)
    }).catch(exception => {
      console.log('Permissions API Exception', exception);
    })
}

export const isModalShow = ({ commit }, status) => {
    commit('SHOW_MODAL', status)
}

export const userFormData = ({ commit }, value) => {
    commit('SET_USER_FORM_DATA', value)
}
