const API_BASE = '/api';

let authToken = '';
let unauthorizedHandler: (() => void) | null = null;

export function setAuthToken(token: string) {
	authToken = token;
}

export function getAuthToken() {
	return authToken;
}

export function setUnauthorizedHandler(handler: (() => void) | null) {
	unauthorizedHandler = handler;
}

async function request<T>(method: string, path: string, body?: unknown, query?: Record<string, string>): Promise<T> {
	const url = new URL(`${API_BASE}${path}`, window.location.origin);
	if (query) {
		for (const [k, v] of Object.entries(query)) {
			if (v !== undefined && v !== null) url.searchParams.set(k, v);
		}
	}

	const opts: RequestInit = {
		method,
		credentials: 'include',
		headers: {
			'Content-Type': 'application/json',
			...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),
		},
	};
	if (body && method !== 'GET') opts.body = JSON.stringify(body);

	const res = await fetch(url.toString(), opts);
	if (res.status === 401) {
		authToken = '';
		try { localStorage.removeItem('mc_token'); } catch {}
		try { sessionStorage.removeItem('mc_token'); } catch {}
		unauthorizedHandler?.();
		throw new Error('Unauthorized');
	}
	const data = await res.json();
	if (!res.ok) throw new Error(data.error || `Request failed (${res.status})`);
	return data as T;
}

export const api = {
	get: <T>(path: string, query?: Record<string, string>) => request<T>('GET', path, undefined, query),
	post: <T>(path: string, body?: unknown) => request<T>('POST', path, body),
	put: <T>(path: string, body?: unknown) => request<T>('PUT', path, body),
	patch: <T>(path: string, body?: unknown) => request<T>('PATCH', path, body),
	del: <T>(path: string, body?: unknown) => request<T>('DELETE', path, body),
};
