import type { TimeEntryInsert, CustomerInsert, ProjectInsert } from "@emberclone/shared" const API_BASE = "/api" async function request(endpoint: string, options: RequestInit = {}): Promise { const token = localStorage.getItem("auth_token") const headers = new Headers(options.headers) if (token) { headers.set("Authorization", `Bearer ${token}`) } headers.set("Content-Type", "application/json") const response = await fetch(`${API_BASE}${endpoint}`, { ...options, headers, credentials: "include" }) if (!response.ok) { const errorData = await response.json().catch(() => ({})) const err: any = new Error(errorData.message || `API Error: ${response.status}`) err.status = response.status throw err } return response.json() } export const api = { async login(email: string, password: string) { const data = await request<{ token: string }>("/auth/login", { method: "POST", body: JSON.stringify({ email, password }) }) if (data?.token) { localStorage.setItem("auth_token", data.token) } return data }, logout() { localStorage.removeItem("auth_token") return request("/auth/logout", { method: "POST" }).catch(() => {}) }, async getMe() { return request<{ id: string; email: string; name: string; role: "admin" | "user" }>("/auth/me") }, async listTimeEntries(opts?: Record) { const query = opts ? `?${new URLSearchParams(opts).toString()}` : "" return request(`/time-entries${query}`) }, async createTimeEntry(data: Partial) { return request("/time-entries", { method: "POST", body: JSON.stringify(data) }) }, async deleteTimeEntry(id: string) { return request(`/time-entries/${id}`, { method: "DELETE" }) }, async listCustomers() { return request( "/customers") }, async createCustomer(data: Partial) { return request("/customers", { method: "POST", body: JSON.stringify(data) }) }, async deleteCustomer(id: string) { return request(`/customers/${id}`, { method: "DELETE" }) }, async listProjects(opts?: Record) { const query = opts ? `?${new URLSearchParams(opts).toString()}` : "" return request(`/projects${query}`) }, async createProject(data: Partial) { return request("/projects", { method: "POST", body: JSON.stringify(data) }) }, async deleteProject(id: string) { return request(`/projects/${id}`, { method: "DELETE" }) } }