const API_BASE = import.meta.env.VITE_API_URL || '';

export function hasToken(): boolean {
	return typeof window !== 'undefined' && !!localStorage.getItem('api_token');
}

export async function api<T>(path: string, options: RequestInit = {}): Promise<T> {
	const token = typeof window !== 'undefined' ? localStorage.getItem('api_token') : null;

	if (!token && typeof window !== 'undefined' && !window.location.pathname.startsWith('/login')) {
		window.location.href = '/login';
		throw new Error('No token');
	}

	const headers: Record<string, string> = {
		...(options.headers as Record<string, string> || {})
	};

	if (token) {
		headers['Authorization'] = `Bearer ${token}`;
	}

	if (options.body && typeof options.body === 'string') {
		headers['Content-Type'] = 'application/json';
	}

	const res = await fetch(`${API_BASE}${path}`, {
		...options,
		headers,
		credentials: 'include'
	});

	if (res.status === 401) {
		if (typeof window !== 'undefined') {
			localStorage.removeItem('api_token');
			window.location.href = '/login';
		}
		throw new Error('Unauthorized');
	}

	return res.json();
}

export function get<T>(path: string) {
	return api<T>(path);
}

export function post<T>(path: string, data: unknown) {
	return api<T>(path, {
		method: 'POST',
		body: JSON.stringify(data)
	});
}
