2025-12-06 19:13:27 -03:00

77 lines
2.0 KiB
TypeScript

import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
import { mydb } from "../../lib/mySupabase.ts";
import { corsHeaders, jsonResponse, errorResponse } from "../../lib/utils.ts";
serve(async (req) => {
if (req.method === "OPTIONS") {
return new Response("ok", { status: 200, headers: corsHeaders() });
}
try {
if (req.method !== "POST") {
return errorResponse("Method not allowed", 405);
}
const body = await req.json();
const {
patient_id,
external_patient_id,
points_earned,
event_type,
reason,
} = body;
// Usar external_patient_id como referência principal
const targetPatientId = external_patient_id || patient_id;
if (!targetPatientId) {
return errorResponse(
"patient_id or external_patient_id is required",
400
);
}
const res = await mydb
.from("patient_rewards")
.select("*")
.eq("external_patient_id", targetPatientId)
.single();
const current = res.data || { points: 0, level: 1 };
const newPoints = current.points + points_earned;
const newLevel = Math.floor(newPoints / 100) + 1;
if (res.data) {
// Update existente
await mydb
.from("patient_rewards")
.update({ points: newPoints, level: newLevel })
.eq("external_patient_id", targetPatientId);
} else {
// Insert novo
await mydb.from("patient_rewards").insert({
external_patient_id: targetPatientId,
points: newPoints,
level: newLevel,
});
}
await mydb.from("patient_journey").insert({
external_patient_id: targetPatientId,
event_type: event_type || "points_earned",
event_data: { points_earned, reason },
points_earned,
});
return jsonResponse({
success: true,
new_points: newPoints,
new_level: newLevel,
level_up: current.level !== newLevel,
});
} catch (error: unknown) {
const err = error as Error;
return errorResponse(err.message, 500);
}
});