2025-10-21 13:02:56 -03:00

198 lines
5.0 KiB
TypeScript

/**
* Netlify Function: Reports
* GET /rest/v1/reports - Lista relatórios
* GET /rest/v1/reports/{id} - Busca por ID
* POST /rest/v1/reports - Cria relatório
* PATCH /rest/v1/reports/{id} - Atualiza relatório
*/
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, 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
const pathParts = event.path.split("/");
const reportId =
pathParts[pathParts.length - 1] !== "reports"
? pathParts[pathParts.length - 1]
: null;
// GET - Listar ou buscar por ID
if (event.httpMethod === "GET") {
let url = `${SUPABASE_URL}/rest/v1/reports`;
if (reportId && reportId !== "reports") {
url += `?id=eq.${reportId}&select=*`;
} else if (event.queryStringParameters) {
const params = new URLSearchParams(
event.queryStringParameters as Record<string, string>
);
url += `?${params.toString()}`;
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();
if (
reportId &&
reportId !== "reports" &&
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 relatório
if (event.httpMethod === "POST") {
const body = JSON.parse(event.body || "{}");
if (!body.patient_id) {
return {
statusCode: 400,
headers,
body: JSON.stringify({
error: "Campo obrigatório: patient_id",
}),
};
}
const response = await fetch(`${SUPABASE_URL}/rest/v1/reports`, {
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();
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 relatório
if (event.httpMethod === "PATCH") {
if (!reportId || reportId === "reports") {
return {
statusCode: 400,
headers,
body: JSON.stringify({ error: "ID do relatório é obrigatório" }),
};
}
const body = JSON.parse(event.body || "{}");
const response = await fetch(
`${SUPABASE_URL}/rest/v1/reports?id=eq.${reportId}`,
{
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),
};
}
return {
statusCode: 405,
headers,
body: JSON.stringify({ error: "Method Not Allowed" }),
};
} catch (error) {
console.error("Erro na API de relatórios:", error);
return {
statusCode: 500,
headers,
body: JSON.stringify({
error: "Erro interno no servidor",
message: error instanceof Error ? error.message : "Erro desconhecido",
}),
};
}
};