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";
import {
  createNotificationSchema,
  notificationFiltersSchema,
} from "../../lib/validation.ts";

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

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

    // Apenas admin, secretária e médico podem criar/ver notificações
    if (!hasPermission(auth.role, ["admin", "secretary", "doctor"])) {
      return errorResponse("Sem permissão para acessar notificações", 403);
    }

    // POST com method GET no body (padrão Supabase callFunction)
    if (req.method === "POST") {
      const body = await req.json();

      // Se é um GET simulado via POST
      if (body.method === "GET") {
        const { status = "pending", type } = body.filters || {};

        let query = mydb.from("notifications_queue").select("*");

        if (status) query = query.eq("status", status);
        if (type) query = query.eq("type", type);

        query = query.order("created_at", { ascending: true });

        const { data, error } = await query;

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

        return jsonResponse(data);
      }

      // POST normal - criar notificação
      const validatedData = createNotificationSchema.parse(body);

      const { data, error } = await mydb
        .from("notifications_queue")
        .insert([validatedData])
        .select();

      // Audit log
      await mydb.from("audit_log").insert({
        user_id: auth.userId,
        action: "create_notification",
        target_type: "notification",
        target_id: data?.[0]?.id,
        payload: validatedData,
      });

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

      return jsonResponse(data[0]);
    }

    if (req.method === "GET") {
      const url = new URL(req.url);
      const status = url.searchParams.get("status") || "pending";

      const { data, error } = await mydb
        .from("notifications_queue")
        .select("*")
        .eq("status", status)
        .order("created_at", { ascending: true });

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

      return jsonResponse(data);
    }

    return errorResponse("Method not allowed", 405);
  } catch (error) {
    console.error("Error in notifications function:", error);
    return errorResponse(error.message);
  }
});
