-- Update trigger function to pass reviewer notes properly
CREATE OR REPLACE FUNCTION public.notify_user_on_submission_status_change()
RETURNS TRIGGER
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public'
AS $function$
DECLARE
  function_url text;
  anon_key text;
BEGIN
  -- Only notify on status changes to approved or rejected
  IF OLD.status IS DISTINCT FROM NEW.status AND NEW.status IN ('approved', 'rejected') THEN
    
    -- Build the function URL
    function_url := 'https://ydvtmnrszybqnbcqbdcy.supabase.co/functions/v1/notify-user-submission-status';
    
    -- Use the public anon key
    anon_key := 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InlkdnRtbnJzenlicW5iY3FiZGN5Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTgzMjYzNTYsImV4cCI6MjA3MzkwMjM1Nn0.DM3oyapd_omP5ZzIlrT0H9qBsiQBxBRgw2tYuqgXKX4';
    
    -- Call edge function asynchronously with reviewer_notes
    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,
        'user_id', NEW.user_id,
        'submission_type', NEW.submission_type,
        'status', NEW.status,
        'reviewer_notes', COALESCE(NEW.reviewer_notes, '')
      )
    );
    
    RAISE LOG 'Triggered user notification for submission % with status %', NEW.id, NEW.status;
  END IF;
  
  RETURN NEW;
EXCEPTION
  WHEN OTHERS THEN
    -- Log error but don't fail the status update
    RAISE WARNING 'Failed to notify user about submission status: %', SQLERRM;
    RETURN NEW;
END;
$function$;