// #region ApiHelper [C:2] [TYPE Module] [SEMANTICS e2e, api, helper, auth]
// @BRIEF Helper for backend API calls in E2E tests (settings CRUD, etc.)
// @RELATION DEPENDS_ON -> [GlobalSetup]

const BACKEND_URL = process.env.BACKEND_URL || 'http://127.0.0.1:8101';

/**
 * Get auth token from env (set during global-setup).
 */
function getToken() {
	return process.env.E2E_TOKEN;
}

/**
 * Make an authenticated GET request to the backend API.
 */
export async function apiGet(path) {
	const token = getToken();
	const res = await fetch(`${BACKEND_URL}${path}`, {
		headers: {
			'Authorization': `Bearer ${token}`,
			'Content-Type': 'application/json',
		},
	});
	if (!res.ok) {
		const body = await res.text().catch(() => '');
		throw new Error(`GET ${path} → ${res.status}: ${body.slice(0, 200)}`);
	}
	return res.json();
}

/**
 * Make an authenticated POST request to the backend API.
 */
export async function apiPost(path, body = {}) {
	const token = getToken();
	const res = await fetch(`${BACKEND_URL}${path}`, {
		method: 'POST',
		headers: {
			'Authorization': `Bearer ${token}`,
			'Content-Type': 'application/json',
		},
		body: JSON.stringify(body),
	});
	if (!res.ok) {
		const text = await res.text().catch(() => '');
		throw new Error(`POST ${path} → ${res.status}: ${text.slice(0, 200)}`);
	}
	return res.status === 204 ? null : res.json();
}

/**
 * Make an authenticated PUT request to the backend API.
 */
export async function apiPut(path, body = {}) {
	const token = getToken();
	const res = await fetch(`${BACKEND_URL}${path}`, {
		method: 'PUT',
		headers: {
			'Authorization': `Bearer ${token}`,
			'Content-Type': 'application/json',
		},
		body: JSON.stringify(body),
	});
	if (!res.ok) {
		const text = await res.text().catch(() => '');
		throw new Error(`PUT ${path} → ${res.status}: ${text.slice(0, 200)}`);
	}
	return res.json();
}

/**
 * Make an authenticated DELETE request to the backend API.
 */
export async function apiDelete(path) {
	const token = getToken();
	const res = await fetch(`${BACKEND_URL}${path}`, {
		method: 'DELETE',
		headers: {
			'Authorization': `Bearer ${token}`,
		},
	});
	if (!res.ok && res.status !== 204) {
		const text = await res.text().catch(() => '');
		throw new Error(`DELETE ${path} → ${res.status}: ${text.slice(0, 200)}`);
	}
	return res.status === 204 ? null : res.json();
}
// #endregion ApiHelper
