-- Enable pg_net extension for HTTP requests from triggers
CREATE EXTENSION IF NOT EXISTS pg_net;

-- Create function to notify moderators when a new submission is created
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;
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';
  
  -- 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 ' || current_setting('request.headers', true)::json->>'authorization'
    ),
    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;
$$;

-- Create trigger on content_submissions
DROP TRIGGER IF EXISTS notify_moderators_on_submission ON public.content_submissions;

CREATE TRIGGER notify_moderators_on_submission
  AFTER INSERT ON public.content_submissions
  FOR EACH ROW
  EXECUTE FUNCTION public.notify_moderators_on_new_submission();

-- Add comment for documentation
COMMENT ON FUNCTION public.notify_moderators_on_new_submission() IS 
  'Automatically notifies all moderators via Novu when a new submission enters the moderation queue';

COMMENT ON TRIGGER notify_moderators_on_submission ON public.content_submissions IS 
  'Triggers moderator notifications for new submissions';