78 lines
2.2 KiB
TypeScript
78 lines
2.2 KiB
TypeScript
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
|
|
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
|
|
import { corsHeaders, jsonResponse, errorResponse } from "../../lib/utils.ts";
|
|
|
|
// Cliente Supabase com SERVICE_ROLE_KEY (bypass RLS)
|
|
const supabaseUrl = Deno.env.get("SUPABASE_URL")!;
|
|
const supabaseKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;
|
|
const supabase = createClient(supabaseUrl, supabaseKey);
|
|
|
|
serve(async (req) => {
|
|
if (req.method === "OPTIONS") {
|
|
return new Response("ok", {
|
|
status: 200,
|
|
headers: corsHeaders(),
|
|
});
|
|
}
|
|
|
|
try {
|
|
if (req.method !== "GET") {
|
|
return errorResponse("Method not allowed", 405);
|
|
}
|
|
|
|
// Extrair patient_id da URL
|
|
const url = new URL(req.url);
|
|
const patientId = url.searchParams.get("external_patient_id");
|
|
|
|
if (!patientId) {
|
|
return errorResponse("external_patient_id is required", 400);
|
|
}
|
|
|
|
console.log(
|
|
"[gamification-patient-streak] Querying for patient:",
|
|
patientId
|
|
);
|
|
|
|
try {
|
|
const { data, error } = await supabase
|
|
.from("patient_rewards")
|
|
.select("*")
|
|
.eq("external_patient_id", patientId)
|
|
.single();
|
|
|
|
if (error) {
|
|
console.warn("[gamification-patient-streak] DB Error:", error);
|
|
// Se não encontrou ou tabela não existe, retorna defaults
|
|
return jsonResponse({
|
|
points: 0,
|
|
level: 1,
|
|
streak_days: 0,
|
|
achievements: [],
|
|
});
|
|
}
|
|
|
|
console.log("[gamification-patient-streak] Success:", data);
|
|
|
|
return jsonResponse({
|
|
points: data?.points || 0,
|
|
level: data?.level || 1,
|
|
streak_days: data?.streak_days || 0,
|
|
achievements: data?.achievements || [],
|
|
});
|
|
} catch (dbError) {
|
|
console.error("[gamification-patient-streak] DB Exception:", dbError);
|
|
// Se tabela não existe ou erro de DB, retorna dados padrão
|
|
return jsonResponse({
|
|
points: 0,
|
|
level: 1,
|
|
streak_days: 0,
|
|
achievements: [],
|
|
});
|
|
}
|
|
} catch (error: unknown) {
|
|
const err = error as Error;
|
|
console.error("[gamification-patient-streak] Error:", err);
|
|
return errorResponse(err.message, 500);
|
|
}
|
|
});
|