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, hasPermission } from "../../lib/auth.ts";

/**
 * POST /notifications/send
 * Enviar notificação (SMS, email, WhatsApp, push)
 * 
 * Body:
 * {
 *   type: 'sms' | 'email' | 'whatsapp' | 'push',
 *   recipient_id?: uuid,
 *   recipient_phone?: string,
 *   recipient_email?: string,
 *   payload: { subject?, body, ... },
 *   scheduled_at?: timestamptz,
 *   priority?: number (1-10)
 * }
 * 
 * Returns:
 * {
 *   success: boolean,
 *   notification_id: uuid,
 *   status: string,
 *   scheduled_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);
    }

    // Apenas staff pode enviar notificações
    if (!hasPermission(auth.role, ["admin", "secretary", "doctor"])) {
      return errorResponse("Sem permissão", 403);
    }

    const body = await req.json();
    const { 
      type, 
      recipient_id, 
      recipient_phone, 
      recipient_email, 
      payload, 
      scheduled_at,
      priority 
    } = body;

    // Validar tipo de notificação
    if (!["sms", "email", "whatsapp", "push"].includes(type)) {
      return errorResponse("Tipo de notificação inválido", 400);
    }

    // Inserir na fila
    const res = await mydb
      .from("notifications_queue")
      .insert({
        type,
        recipient_id,
        recipient_phone,
        recipient_email,
        payload,
        status: scheduled_at ? "scheduled" : "pending",
        scheduled_at: scheduled_at || new Date().toISOString(),
        priority: priority || 5,
      })
      .select();

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

    // Audit log
    await mydb.from("audit_log").insert({
      user_id: auth.userId,
      action: "send_notification",
      target_type: "notification",
      target_id: res.data?.[0]?.id,
      payload: { type, recipient_id, scheduled: !!scheduled_at },
    });

    return jsonResponse({
      success: true,
      notification_id: res.data?.[0]?.id,
      status: res.data?.[0]?.status,
      scheduled_at: res.data?.[0]?.scheduled_at,
    });
  } catch (error: unknown) {
    console.error("[send]", error);
    const err = error as Error;
    return errorResponse(err.message, 500);
  }
});
