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";
import { validateAuth } from "../../lib/auth.ts";

serve(async (req) => {
  if (req.method === "OPTIONS") {
    return new Response("ok", { headers: corsHeaders() });
  }

  try {
    const auth = await validateAuth(req);
    if (!auth) {
      return errorResponse("Não autorizado", 401);
    }

    if (req.method !== "POST") {
      return errorResponse("Method not allowed", 405);
    }

    const body = await req.json();
    const { patient_id, points_earned, event_type, reason } = body;

    const res = await mydb
      .from("patient_rewards")
      .select("*")
      .eq("patient_id", patient_id || auth.userId)
      .single();

    const current = res.data || { points: 0, level: 1 };
    const newPoints = current.points + points_earned;
    const newLevel = Math.floor(newPoints / 100) + 1;

    await mydb
      .from("patient_rewards")
      .update({ points: newPoints, level: newLevel })
      .eq("patient_id", patient_id || auth.userId);

    await mydb.from("patient_journey").insert({
      patient_id: patient_id || auth.userId,
      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);
  }
});
