-- Fix the trigger function to use the anon key directly
CREATE OR REPLACE FUNCTION public.notify_moderators_on_new_submission()
RETURNS TRIGGER
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
  submitter_profile record;
  function_url text;
  anon_key text;
BEGIN
  -- Get submitter's username or display name
  SELECT username, display_name INTO submitter_profile
  FROM public.profiles
  WHERE user_id = NEW.user_id;
  
  -- Build the function URL
  function_url := 'https://ydvtmnrszybqnbcqbdcy.supabase.co/functions/v1/notify-moderators-submission';
  
  -- Use the public anon key (this is safe, it's already public in the frontend)
  anon_key := 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InlkdnRtbnJzenlicW5iY3FiZGN5Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTgzMjYzNTYsImV4cCI6MjA3MzkwMjM1Nn0.DM3oyapd_omP5ZzIlrT0H9qBsiQBxBRgw2tYuqgXKX4';
  
  -- Call edge function asynchronously (doesn't block submission)
  -- Using pg_net to make HTTP request without blocking
  PERFORM net.http_post(
    url := function_url,
    headers := jsonb_build_object(
      'Content-Type', 'application/json',
      'Authorization', 'Bearer ' || anon_key,
      'apikey', anon_key
    ),
    body := jsonb_build_object(
      'submission_id', NEW.id,
      'submission_type', NEW.submission_type,
      'submitter_name', COALESCE(submitter_profile.display_name, submitter_profile.username, 'Anonymous'),
      'action', COALESCE((NEW.content->>'action')::text, 'create')
    )
  );
  
  RETURN NEW;
EXCEPTION
  WHEN OTHERS THEN
    -- Log error but don't fail the submission
    RAISE WARNING 'Failed to notify moderators: %', SQLERRM;
    RETURN NEW;
END;
$$;

-- Add comment
COMMENT ON FUNCTION public.notify_moderators_on_new_submission() IS 
  'Automatically notifies all moderators via Novu when a new submission enters the moderation queue. Fixed to use anon key directly.';