document.addEventListener("DOMContentLoaded", function () { const apiBase = "/api"; async function apiFetch(endpoint, options = {}) { const token = localStorage.getItem("token"); const headers = { "Content-Type": "application/json", ...options.headers, }; if (token) { headers["Authorization"] = `Bearer ${token}`; } const response = await fetch(`${apiBase}${endpoint}`, { ...options, headers, }); if (!response.ok) { throw new Error(`API error: ${response.status}`); } return response.json(); } window.LinkSync = { apiFetch, async getLinks(params = {}) { const qs = new URLSearchParams(params).toString(); return apiFetch(`/links/?${qs}`); }, async createLink(data) { return apiFetch("/links/", { method: "POST", body: JSON.stringify(data), }); }, async updateLink(id, data) { return apiFetch(`/links/${id}`, { method: "PUT", body: JSON.stringify(data), }); }, async deleteLink(id) { return apiFetch(`/links/${id}`, { method: "DELETE" }); }, async getCollections() { return apiFetch("/collections/"); }, async createCollection(data) { return apiFetch("/collections/", { method: "POST", body: JSON.stringify(data), }); }, async executeQuery(expression, limit = 20) { return apiFetch(`/queries/execute?expression=${encodeURIComponent(expression)}&limit=${limit}`); }, async login(username, password) { const formData = new URLSearchParams(); formData.append("username", username); formData.append("password", password); const response = await fetch(`${apiBase}/auth/login`, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: formData.toString(), }); if (!response.ok) throw new Error("Login failed"); const data = await response.json(); localStorage.setItem("token", data.access_token); return data; }, logout() { localStorage.removeItem("token"); }, }; });