import qs from 'qs';
import axios from 'axios';
import AsyncStorage from '@react-native-community/async-storage';

const pack = require('../../package.json');

export function token({host = '', key, secret, device}) {
  return axios.post(`${host}/store/auth`, qs.stringify({key, secret, device}));
}

export async function refreshToken() {
  const auth = await AsyncStorage.getItem('auth');
  if (auth) {
    try {
      const {refresh_token} = JSON.parse(auth);
      return await axios.get('/auth/refresh', {
        headers: {Authorization: `Bearer ${refresh_token}`},
      });
    } catch (e) {
      return {data: null};
    }
  }
  return {data: null};
}

export function version() {
  return axios.put('/store/version', qs.stringify({version: pack.version}));
}

export function region() {
  return axios.get('/store/region');
}

export function door({userId}) {
  return axios.post('/store/door', qs.stringify({userId}));
}

export function wxdoor({userId, openid, wxtoken, nickname, fToken}) {
  return axios.post(
    '/store/wxdoor',
    qs.stringify({userId, openid, wxtoken, nickname, fToken}),
  );
}

export function scaleData() {
  return axios.get('/store/scaleData');
}

export function sendsms({phone}) {
  return axios.post('/store/sendsms', qs.stringify({phone}));
}

export function verifysms({phone, code, userId}) {
  return axios.post('/store/verifysms', qs.stringify({phone, code, userId}));
}

export function getAdvertising(action) {
  return axios.get(`/store/advertising?${qs.stringify(action)}`);
}
