import axios from 'axios'
import store from '~store'

const service = axios.create({
  withCredentials: true,
  baseUrl: '/'
})

service.interceptors.request.use(config => {
  // is server render, use ${baseUrl} directly rather than ${proxyUrl}
  if (typeof window === 'undefined') {
    config.url = process.env.baseUrl + '/city/' + process.env.cityDomain + config.url
    config.headers.cookie = store.state.option.cookies + '; ' + store.state.option.sessionId
    config.headers['User-Agent'] = store.state.option.userAgent
  } else {
    config.url = '/city/' + process.env.cityDomain + config.url
  }

  return config
}, error => {
  return Promise.reject(error)
})

service.interceptors.response.use(response => {
  const cookies = response.headers['set-cookie']
  if (cookies && cookies.length) {
    for (let i = 0; i < cookies.length; i++) {
      if (cookies[i].indexOf('JSESSIONID') > -1) {
        const sessionId = cookies[i]
        const first = sessionId.indexOf(';')
        const second = sessionId.lastIndexOf(';')
        const newSessionId = sessionId.replace(sessionId.substring(first, second), '')
        store.commit('option/SET_SESSION_ID', newSessionId)
        break
      }
    }
  }
  return response
}, error => {
  return Promise.reject(error)
})

export default service
