import { setRoute } from './actions-route'

export const AUTH_USER = 'AUTH_USER'
export const AUTH_ERROR = 'AUTH_ERROR'
export const FETCH_USER = 'FETCH_USER'

export const signup = formProps => async dispatch => {
  try {
    const response = await fetch(`/signup`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(formProps)
    })

    if (response.ok) {
      const data = await response.json()

      if (data && data.error) {
        dispatch(authError(data.error))
      }
      if (data && data.token) {
        // localStorage.setItem('access_token', data.token)

        /* 사용자 auth dispatch 후에 바로 사용자 정보를 서버에 요청함. */
        dispatch(authUser(data.token))
        return dispatch(authcheck())

        // window.dispatchEvent(
        //   new CustomEvent('vaadin-router-go', {
        //     detail: { pathname: '/users/me' }
        //   })
        // )
      } else {
        throw new Error(response.status)
      }
    }
  } catch (e) {
    return dispatch(authError(e))
  }
}

export const signin = formProps => async dispatch => {
  try {
    const response = await fetch(`/signin`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(formProps)
    })

    if (response.ok) {
      const data = await response.json()

      // localStorage.setItem('access_token', data.token)

      /* 사용자 auth dispatch 후에 바로 사용자 정보를 서버에 요청함. */
      dispatch(authUser(data.token))
      dispatch(authcheck())
    } else {
      throw new Error(response.status)
    }
  } catch (e) {
    return dispatch(authError(e))
  }
}

export const authcheck = () => async dispatch => {
  try {
    const response = await fetch(`/authcheck`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (response.ok) {
      const data = await response.json()

      // localStorage.setItem('user', JSON.stringify(data.user))
      // localStorage.setItem('access_token', data.token)

      dispatch(fetchUser(data.user, data.token))
    } else {
      throw new Error(response.status)
    }
  } catch (e) {
    dispatch(authError(e))
    /* authcheck에 실패하면, signin 페이지로 이동한다. */
    return dispatch(setRoute('signin'))
  }
}

export const signout = () => async dispatch => {
  // localStorage.removeItem('access_token')
  // localStorage.removeItem('user')

  document.cookie = 'access_token=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'

  dispatch(authUser(''))
  return dispatch(setRoute('signin'))
}

const fetchUser = (user, token) => {
  return {
    type: FETCH_USER,
    user,
    token
  }
}

const authUser = token => {
  return {
    type: AUTH_USER,
    token
  }
}

export const authError = error => {
  return {
    type: AUTH_ERROR,
    error: error.message
  }
}
