import type { LinkEntry } from "../../common/lib"; const API_BASE = location.hostname == "localhost" || location.hostname == "127.0.0.1" ? "http://localhost:3001" : ""; interface ApiResponse { success: boolean; data?: T; error?: string; } function getAuthHeader() { const password = localStorage.getItem("password"); if (!password) throw new Error("No password found in localStorage"); return { "X-Password": password }; } async function request(url: string, options: RequestInit = {}): Promise> { const headers = { ...options.headers, ...getAuthHeader() }; let res: Response; try { res = await fetch(`${API_BASE}/api/${url}`, { ...options, headers }); } catch { return { success: false, error: "Network error" }; } let json = null; try { json = await res.json(); } catch { return { success: false, error: `Server returned status ${res.status}` }; } if (!res.ok) { return { success: false, error: json?.error || `Request failed with status ${res.status}` }; } return { success: true, data: json as T }; } export async function login(password: string): Promise> { localStorage.setItem("password", password); const res = await request(`login`, { method: "POST" }); return res; } export async function logout(): Promise> { localStorage.removeItem("password"); return { success: true }; } export async function getLinks(): Promise> { return request("links"); } export async function getLink(id: string): Promise> { return request(`links/${id}`); } export async function createLink(link: Partial): Promise> { return request("links", { method: "POST", body: JSON.stringify(link), headers: { "Content-Type": "application/json" }, }); } export async function updateLink(id: string, link: Partial): Promise> { return request(`links/${id}`, { method: "PUT", body: JSON.stringify(link), headers: { "Content-Type": "application/json" }, }); } export async function deleteLink(id: string): Promise> { return request(`links/${id}`, { method: "DELETE" }); } export async function getLinkStats(id: string): Promise> { return request<{ clicks: number }>(`links/${id}/stats`); }