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

export function getToken(): string | null {
	return typeof window !== 'undefined' ? localStorage.getItem('session_token') : null;
}

export function hasToken(): boolean {
	return !!getToken();
}

export async function api<T>(path: string, options: RequestInit = {}): Promise<T> {
	const token = getToken();

	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('session_token');
			window.location.href = '/login';
		}
		throw new Error('Unauthorized');
	}

	if (!res.ok) {
		const err = await res.json().catch(() => ({ error: res.statusText }));
		throw new Error(err.error || `HTTP ${res.status}`);
	}

	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) });
}

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

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

export function del<T>(path: string) {
	return api<T>(path, { method: 'DELETE' });
}

export function today(): string {
	return new Date().toISOString().split('T')[0];
}

export function formatDate(d: string): string {
	return new Date(d + 'T00:00:00').toLocaleDateString('en-US', {
		weekday: 'short', month: 'short', day: 'numeric'
	});
}
