import { goto } from '$app/navigation';
import { userStore } from './UserStore.svelte';

export function preventDefault<T extends Event, Return>(f: (e: T) => Return): (e: T) => Return {
	return (e: T): Return => {
		e.preventDefault();
		return f(e);
	};
}

export async function request(
	method: 'POST' | 'PUT' | 'GET' | 'DELETE',
	url: string,
	body?: unknown
) {
	const headers = new Headers();
	headers.append('response-type', 'application/json');

	if (body) {
		headers.append('content-type', 'application/json');
	}

	if (userStore.isLoggedIn) {
		headers.append('token', userStore.token);
	}

	const r = await fetch(`/api/${url}`, {
		method,
		headers,
		body: JSON.stringify(body)
	});

	if (r.status === 401) {
		userStore.user = undefined;
		goto('/login');
		return;
	}

	if (r.status !== 200) {
		throw r;
	}

	return r.json();
}

export async function get(url: string) {
	return request('GET', url);
}

export async function deleteR(url: string) {
	return request('DELETE', url);
}

export async function post(url: string, body: unknown) {
	return request('POST', url, body);
}

export async function put(url: string, body: unknown) {
	return request('PUT', url, body);
}
