import { authStore } from '$lib/stores/auth.svelte';

/**
 * Returns an Authorization header object if the user is authenticated, or undefined otherwise.
 *
 * Can be spread directly into a fetch() headers object:
 *   fetch('/api/...', { headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } })
 *
 * Or used standalone for auth-only headers:
 *   fetch('/api/...', { headers: getAuthHeaders() })
 *
 * Spreading `undefined` is a safe no-op in modern JS environments.
 */
export function getAuthHeaders(): { Authorization: string } | undefined {
	const token = authStore.currentToken;
	return token ? { Authorization: `Bearer ${token}` } : undefined;
}

/**
 * Drop-in wrapper around fetch() that automatically includes the auth token
 * when available. Preserves any headers, method, body, etc. passed in `init`.
 *
 * Use this for all authenticated API calls. Public endpoints should continue
 * using bare fetch() to avoid sending an unnecessary Authorization header.
 *
 * @example
 *   const res = await apiFetch('/api/user/profile');
 *   const data = await apiFetch('/api/bookings/reserve', {
 *     method: 'POST',
 *     body: JSON.stringify({ start_time, service_ids }),
 *   });
 */
export async function apiFetch(url: string | URL | Request, init?: RequestInit): Promise<Response> {
	const headers = new Headers(init?.headers);

	const authHeaders = getAuthHeaders();
	if (authHeaders) {
		headers.set('Authorization', authHeaders.Authorization);
	}

	return fetch(url, { ...init, headers });
}
