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";

/**
 * POST /notifications/confirm
 * Confirmar leitura/recebimento de notificação
 *
 * Body:
 * {
 *   notification_id: uuid,
 *   read_at?: timestamptz,
 *   clicked?: boolean
 * }
 *
 * Returns:
 * {
 *   success: boolean,
 *   notification_id: uuid,
 *   confirmed_at: timestamptz
 * }
 */

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 { notification_id, read_at, clicked } = body;

    // Atualizar notificação
    const res = await mydb
      .from("notifications_queue")
      .update({
        status: "sent",
        sent_at: read_at || new Date().toISOString(),
      })
      .eq("id", notification_id)
      .select();

    if (res.error) {
      return errorResponse(res.error.message);
    }

    // Registrar em telemetria
    if (clicked) {
      await mydb.from("telemetry").insert({
        event_name: "notification_clicked",
        event_category: "engagement",
        user_id: auth.userId,
        properties: { notification_id },
      });
    }

    // Audit log
    await mydb.from("audit_log").insert({
      user_id: auth.userId,
      action: "confirm_notification",
      target_type: "notification",
      target_id: notification_id,
      payload: { clicked },
    });

    return jsonResponse({
      success: true,
      notification_id,
      confirmed_at: new Date().toISOString(),
    });
  } catch (error: unknown) {
    console.error("[confirm]", error);
    const err = error as Error;
    return errorResponse(err.message, 500);
  }
});
