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

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

export function token({key, secret, device}) {
  return axios.post('/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}));
}
