import axios from 'axios';

const getToken = () => {
    return localStorage.getItem('bearerToken');
};

export const setToken = (token) => {
    localStorage.setItem('bearerToken', token);
};

const api = axios.create({
    baseURL: 'https://carsharing.kolei.ru',
    headers: {
        'Access-Control-Allow-Origin': '*',
    },
});

api.interceptors.request.use(function (config) {
    if (getToken()) {
        config.headers.Authorization = `Bearer ${getToken()}`;
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});

export const signin = (data) => {
    return api.post('/auth/login', data);
};

export const signup = (data) => {
    return api.post('/auth/register', data);
};

export const getUserInfo = () => {
    return api.get('/user');
};

export const getCars = () => {
    return api.get('/cars');
}

export const uploadDocument = (formData) => {
    formData.append('token', getToken());
    
    return api.post('https://carsharing.kolei.ru/user/photo', formData, {
        headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': `Bearer ${getToken()}`
        }
    });
};