// functions/api/[[catchall]].js export async function onRequest(context) { const { request, env } = context; const url = new URL(request.url); const path = url.pathname.replace("/api", ""); const method = request.method; // Auth if (path === "/auth" && method === "POST") { const body = await request.json().catch(() => ({})); if (body.password === "admin") { return Response.json({ ok: true, token: "token-" + Date.now() }); } return Response.json({ error: "Password errata" }, { status: 401 }); } if (path === "/me" && method === "GET") { return Response.json({ ok: true }); } // Clients if (path === "/clients" && method === "GET") { const result = await env.DB.prepare("SELECT * FROM clients ORDER BY last_name, first_name").all(); return Response.json(result.results || []); } if (path === "/clients" && method === "POST") { const { first_name, last_name, phone, email, address } = await request.json(); await env.DB.prepare("INSERT INTO clients (first_name, last_name, phone, email, address) VALUES (?,?,?,?,?)") .bind(first_name, last_name, phone, email, address).run(); return Response.json({ ok: true }); } const clientMatch = path.match(/^\/clients\/(\d+)$/); if (clientMatch && method === "GET") { const result = await env.DB.prepare("SELECT * FROM clients WHERE id=?").bind(clientMatch[1]).first(); return Response.json(result || {}); } if (clientMatch && method === "PUT") { const { first_name, last_name, phone, email, address } = await request.json(); await env.DB.prepare("UPDATE clients SET first_name=?, last_name=?, phone=?, email=?, address=? WHERE id=?") .bind(first_name, last_name, phone, email, address, clientMatch[1]).run(); return Response.json({ ok: true }); } if (clientMatch && method === "DELETE") { await env.DB.prepare("DELETE FROM clients WHERE id=?").bind(clientMatch[1]).run(); return Response.json({ ok: true }); } // Appointments if (path === "/appointments" && method === "GET") { const result = await env.DB.prepare("SELECT * FROM appointments ORDER BY date DESC").all(); return Response.json(result.results || []); } if (path === "/appointments" && method === "POST") { const { date, type, notes } = await request.json(); await env.DB.prepare("INSERT INTO appointments (date, type, notes) VALUES (?,?,?)") .bind(date, type, notes).run(); return Response.json({ ok: true }); } return Response.json({ error: "Not found" }, { status: 404 }); }