import {
    constructUrl,
    formatPostData,
    parseQueryParams,
    request,
    unwrapJson,
    validateResponse,
} from './helpers.js';

import { API_URL } from '../constants/constants.js';

const DefaultRequestOptions = {};

export const API_ENDPOINTS = {
    // Events and Items
    GET_EVENTS: '/events',
    //   GET_ITEMS: '/items?eventId=:event_id',
    GET_ITEMS: '/items',

    // Auction Interactions
    //   GET_STATUS: '/auction/:event_id',
    GET_STATUS: '/auction',
    PLACE_BID: '/bids',
    PURCHASE_ITEM: '/sales',

    // User/Profile
    USER_SIGNUP: '/signup',
    USER_PROFILE: '/users/:user_id',

    VALIDATE_SIGNUP_EMAIL: '/signup/validate/email',
    VALIDATE_SIGNUP_NOM: '/signup/validate/nom',

    // Services
    APPLE_SIGNUP: '/auth/apple/login',
    APPLE_LINK: '/auth/apple/link',
    FACEBOOK_SIGNUP: '/auth/facebook/login',
    FACEBOOK_LINK: '/auth/facebook/link',
    GOOGLE_SIGNUP: '/auth/google/login',
    GOOGLE_LINK: '/auth/google/link',
};

const cacheBuster = () => {
    const timestamp = String(Date.now());
    return `?buster=${timestamp}`;
};

export const getEndpointUrl = (endpoint) => {
    if (!endpoints[endpoint]) {
        throw new Error('Invalid API endpoint specified');
    }

    return `${API_URL}${endpoints[endpoint]}`; //`${cacheBuster()}`;
};

export const requestGet = (path, queryParams = [], requestOptions = {}) => {
    const params = parseQueryParams(queryParams);

    if (params === null) {
        throw new Error('Invalid queryParams');
    }

    return request(constructUrl(path, params), {
        ...DefaultRequestOptions,
        ...requestOptions,
    })
        .then(validateResponse)
        .then(unwrapJson);
};

export const requestPost = (options) => {
    const {
        path,
        body = {},
        queryParams = [],
        requestOptions = {},
        isFormattedPostData = false,
    } = options;

    const params = parseQueryParams(queryParams || []);

    if (params === null) {
        throw new Error('invalid queryParams');
    }

    // Additional formatting happens in `formatPostData()`
    // like handling what jQuery calls `traditional` form data
    return request(constructUrl(path, params), {
        ...DefaultRequestOptions,
        ...requestOptions,
        method: 'POST',
        body: isFormattedPostData ? body : formatPostData(body),
    })
        .then(validateResponse)
        .then(unwrapJson);
};
