/**
 * API Helper
 */
import { api } from './config';
import axios from 'axios';

/**
 * Create API instance
 */
const apiClient = axios.create({
    baseURL: api.baseURL,
    timeout: api.timeout,
    headers: {
        ...api.headers
    }
});

/**
 * Helper for URL path
 * @param {string} path 
 * @returns {string}
 */
export const url = (path = '') => {
    // Remove leading slash if present
    path = path.replace(/^\/+/, '');
    return path ? `${api.baseURL}/${path}` : api.baseURL;
};

/**
 * Helper for asset URL (for images, etc)
 * @param {string} path 
 * @returns {string}
 */
export const asset = (path = '') => {
    // Remove leading slash if present
    path = path.replace(/^\/+/, '');
    const baseURL = api.baseURL.replace('/api', '');
    return path ? `${baseURL}/${path}` : baseURL;
};

/**
 * API methods
 */
export default {
    /**
     * Get request
     * @param {string} path 
     * @param {object} params 
     * @returns {Promise}
     */
    get(path, params = {}) {
        return apiClient.get(path, { params });
    },

    /**
     * Post request
     * @param {string} path 
     * @param {object} data 
     * @returns {Promise}
     */
    post(path, data = {}) {
        return apiClient.post(path, data);
    },

    /**
     * Put request
     * @param {string} path 
     * @param {object} data 
     * @returns {Promise}
     */
    put(path, data = {}) {
        return apiClient.put(path, data);
    },

    /**
     * Delete request
     * @param {string} path 
     * @param {object} params 
     * @returns {Promise}
     */
    delete(path, params = {}) {
        return apiClient.delete(path, { params });
    },

    /**
     * Get full URL
     * @param {string} path 
     * @returns {string}
     */
    url: url,

    /**
     * Get asset URL
     * @param {string} path 
     * @returns {string}
     */
    asset: asset
};