/** * Netlify Function: Doctors CRUD * GET /rest/v1/doctors - Lista médicos * GET /rest/v1/doctors/{id} - Busca por ID * POST /rest/v1/doctors - Cria médico * PATCH /rest/v1/doctors/{id} - Atualiza médico * DELETE /rest/v1/doctors/{id} - Deleta médico */ import type { Handler, HandlerEvent } from "@netlify/functions"; const SUPABASE_URL = "https://yuanqfswhberkoevtmfr.supabase.co"; const SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ"; export const handler: Handler = async (event: HandlerEvent) => { const headers = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "Content-Type, Authorization", "Access-Control-Allow-Methods": "GET, POST, PATCH, DELETE, OPTIONS", }; if (event.httpMethod === "OPTIONS") { return { statusCode: 200, headers, body: "", }; } try { const authHeader = event.headers.authorization || event.headers.Authorization; if (!authHeader) { return { statusCode: 401, headers, body: JSON.stringify({ error: "Token não fornecido" }), }; } // Extrai ID da URL se houver (doctors/123 ou doctors?id=123) const pathParts = event.path.split("/"); const doctorId = pathParts[pathParts.length - 1] !== "doctors" ? pathParts[pathParts.length - 1] : null; // GET - Listar ou buscar por ID if (event.httpMethod === "GET") { let url = `${SUPABASE_URL}/rest/v1/doctors`; if (doctorId && doctorId !== "doctors") { // Buscar por ID específico url += `?id=eq.${doctorId}&select=*`; } else if (event.queryStringParameters) { // Adiciona filtros da query string const params = new URLSearchParams( event.queryStringParameters as Record ); url += `?${params.toString()}`; // Adiciona select=* se não tiver if (!params.has("select")) { url += url.includes("?") ? "&select=*" : "?select=*"; } } else { url += "?select=*"; } const response = await fetch(url, { method: "GET", headers: { apikey: SUPABASE_ANON_KEY, Authorization: authHeader, }, }); let data = await response.json(); // Se buscar por ID, retorna o objeto diretamente (não array) if ( doctorId && doctorId !== "doctors" && Array.isArray(data) && data.length > 0 ) { data = data[0]; } return { statusCode: response.status, headers: { ...headers, "Content-Type": "application/json", }, body: JSON.stringify(data), }; } // POST - Criar médico if (event.httpMethod === "POST") { const body = JSON.parse(event.body || "{}"); if ( !body.crm || !body.crm_uf || !body.full_name || !body.cpf || !body.email ) { return { statusCode: 400, headers, body: JSON.stringify({ error: "Campos obrigatórios: crm, crm_uf, full_name, cpf, email", }), }; } const response = await fetch(`${SUPABASE_URL}/rest/v1/doctors`, { method: "POST", headers: { apikey: SUPABASE_ANON_KEY, Authorization: authHeader, "Content-Type": "application/json", Prefer: "return=representation", }, body: JSON.stringify(body), }); let data = await response.json(); // Supabase retorna array, pega o primeiro if (Array.isArray(data) && data.length > 0) { data = data[0]; } return { statusCode: response.status, headers: { ...headers, "Content-Type": "application/json", }, body: JSON.stringify(data), }; } // PATCH - Atualizar médico if (event.httpMethod === "PATCH") { if (!doctorId || doctorId === "doctors") { return { statusCode: 400, headers, body: JSON.stringify({ error: "ID do médico é obrigatório" }), }; } const body = JSON.parse(event.body || "{}"); const response = await fetch( `${SUPABASE_URL}/rest/v1/doctors?id=eq.${doctorId}`, { method: "PATCH", headers: { apikey: SUPABASE_ANON_KEY, Authorization: authHeader, "Content-Type": "application/json", Prefer: "return=representation", }, body: JSON.stringify(body), } ); let data = await response.json(); if (Array.isArray(data) && data.length > 0) { data = data[0]; } return { statusCode: response.status, headers: { ...headers, "Content-Type": "application/json", }, body: JSON.stringify(data), }; } // DELETE - Deletar médico if (event.httpMethod === "DELETE") { if (!doctorId || doctorId === "doctors") { return { statusCode: 400, headers, body: JSON.stringify({ error: "ID do médico é obrigatório" }), }; } const response = await fetch( `${SUPABASE_URL}/rest/v1/doctors?id=eq.${doctorId}`, { method: "DELETE", headers: { apikey: SUPABASE_ANON_KEY, Authorization: authHeader, }, } ); return { statusCode: response.status, headers, body: "", }; } return { statusCode: 405, headers, body: JSON.stringify({ error: "Method Not Allowed" }), }; } catch (error) { console.error("Erro na API de médicos:", error); return { statusCode: 500, headers, body: JSON.stringify({ error: "Erro interno no servidor", message: error instanceof Error ? error.message : "Erro desconhecido", }), }; } };