import { getCookie } from '../utils.js'
import { toast } from 'vue3-toastify'

const restURL = import.meta.env.PROD ? "https://clyde.herisson.ovh/api" : "http://localhost:8080"

export async function restGet(endPoint) {
	return await _rest(endPoint, {method: "GET"});
}

export async function restPost(endPoint, data) {
	return await _rest(endPoint, {method: "POST", body: data});
}

export async function restDelete(endPoint, data) {
	return await _rest(endPoint, {method: "DELETE", body: data});
}

export async function restPatch(endPoint, data) {
	return await _rest(endPoint, {method: "PATCH", body: data});
}

/**
 * backbone for the request made by the frontend
 *
 * specification
 *  - If the user has "session_token" cookie set, it will use it in the authorization field of the http request
 *  - The result will be returned as a json to access fields easily ( the backend should send json response )
 *
 *  @Example _rest("/ping", {user: data}) -> {id:0, txt:"pong"}
 */
async function _rest(endPoint, config){
	endPoint.at(0) != "/" ? console.error("Carefull, you certainly should put a / at the begenning of your endPoint ") : true;
	let session_token = getCookie("session_token");
	let headers = new Headers({'Authorization': session_token});
	config['headers'] = headers;
	return toast.promise(fetch(restURL + endPoint, config),
		{
			pending: config['pending'] != null ? config['pending'] : 'pending',
			error: config['error'] != null ? config['error'] : 'Network Failure...',
			success: config['success'] != null ? config['success'] : {render(res){
				return res.ok ? "Success" : "error";
			}},
		})
		.then( e => e.json()).catch( e => e );
}