import { toast } from 'react-toastify';
const axios = require('axios');
axios.defaults.baseURL = 'http://localhost:3000/api';

const error = (message:string) =>
  toast.error(`🔥 ${message}!`, {
    position: 'bottom-left',
    autoClose: 3000,
    hideProgressBar: false,
    closeOnClick: true,
    pauseOnHover: true,
    draggable: true,
    progress: undefined,
  });

const success = (message:string) =>
  toast.success(`âš¡ ${message}`, {
    position: 'bottom-left',
    autoClose: 3000,
    hideProgressBar: false,
    closeOnClick: true,
    pauseOnHover: true,
    draggable: true,
    progress: undefined,
  });

const setToken = {
  set(token:string) {
    axios.defaults.headers.common.Authorization = `Bearer ${token}`;
  },
  unset() {
    axios.defaults.headers.common.Authorization = '';
  },
};

const authorizeUser = async (number:string,country:string):Promise<string | undefined> => {
  try {
    const { data : {data} } = await axios.post('/auth/register', { number,country });
    success(`check ${number}`);
    return data
  } catch (e) {
    error('BAD REQUEST');
  }
};

const loginUser = async <T>(number:string,code:string):Promise<T | undefined> => {
  try {
    const { data : {data} } = await axios.post('/auth/login', { number,code });
    success(`AUTHORIZED`);
    return data
  } catch (e) {
    error('UNAUTHORIZED');
  }
};

const updateCredentials = async <T>(name: string,lastName: string):Promise<T | undefined> => {
  try {
    const { data : {data} } = await axios.patch('/users/current', { name, lastName });
    success(`CREDENTIALS UPDATED`);
    return data
  } catch (e) {
    error('BAD REQUEST');
  }
};

const updateUserAvatar = async <T>(formData: object): Promise<T | undefined> => {
  try {
    const { data : {data} } = await axios.patch('/users/avatars', formData);
    success(`AVATAR UPDATED`);
    return data
  } catch (e) {
    error('BAD REQUEST');
  } 
};

const currentUser = async <T>(): Promise<T | undefined> => {
  try {
    const { data : {data} } = await axios.get('/users/current');
    success(`LOGIN`);
    return data
  } catch (e) {
    error('BAD REQUEST');
  } 
};

const addContact = async <T>(number:string): Promise<T | undefined> => {
  try {
    const { data : {data} } = await axios.post('/contacts', { number });
    success('CONTACT ADDED');
    return data
  } catch (e) {
    error('BAD REQUEST');
  }
};

const getContacts = async <T>(): Promise<T | undefined> => {
  try {
    const { data : {data} } = await axios.get('/contacts');
    success('CONTACTS LOADED');
    return data
  } catch (e) {
    error('BAD REQUEST');
  }
};



export {
  setToken,
  authorizeUser,
  loginUser,
  updateCredentials,
  updateUserAvatar,
  currentUser,
  addContact,
  getContacts
};