import { axiosInstance } from 'boot/axios'
export const login = function ({ commit }, user) {
  return new Promise((resolve, reject) => {
    commit('AUTH_REQUEST')
    window.axios
      .post('/login', {
        email: user.email,
        password: user.password
      })
      .then(resp => {
        const token = resp.data.token
        const user = resp.data.user
        commit('AUTH_SUCCESS', { token, user })
        resolve(resp)
      })
      .catch((err) => {
        commit('AUTH_ERROR')
        reject(err)
      })
  })
}
export const socialLogin = function ({ commit }, user) {
  return new Promise((resolve, reject) => {
    commit('AUTH_REQUEST')
    window.axios
      .post('/social/login', {
        id: user.id
      })
      .then(resp => {
        const token = resp.data.token
        const user = resp.data.user
        commit('AUTH_SUCCESS', { token, user })
        resolve(resp)
      })
      .catch((err) => {
        commit('AUTH_ERROR')
        reject(err)
      })
  })
}
export const register = function ({ commit }, user) {
  return new Promise((resolve, reject) => {
    commit('AUTH_REQUEST')
    axiosInstance
      .post('/register', user)
      .then(resp => {
        const token = resp.data.token
        const user = resp.data.user
        commit('AUTH_SUCCESS', { token, user })
        resolve(resp)
      })
      .catch((err) => {
        commit('AUTH_ERROR')
        reject(err)
      })
  })
}
export const logout = function ({ commit }) {
  return new Promise((resolve, reject) => {
    commit('AUTH_REQUEST')
    axiosInstance
      .post('/logout')
      .then(() => {
        commit('AUTH_LOGOUT')
        resolve('success')
      })
      .catch(err => {
        commit('AUTH_ERROR')
        reject(err)
      })
  })
}
export const fetchLoggedInUserInfo = function ({ commit }) {
  return new Promise((resolve, reject) => {
    commit('AUTH_REQUEST')
    axiosInstance
      .get('/auth/user')
      .then(resp => {
        const user = resp.data.user
        const token=axiosInstance.defaults.headers.common.Authorization
        commit('AUTH_SUCCESS_SSR', { user })
        resolve(resp)
      })
      .catch((err) => {
        commit('AUTH_ERROR')
        reject(err)
      })
  })
}
