-- Fix notify_moderators_on_new_submission trigger to work with relational data model
-- Removes references to non-existent NEW.content column

CREATE OR REPLACE FUNCTION public.notify_moderators_on_new_submission()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public'
AS $function$
DECLARE
  submitter_profile record;
  base_url text;
  edge_function_url text;
  content_preview text;
  has_photos boolean := false;
  item_count integer := 0;
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 simple content preview based on submission type
  content_preview := CASE NEW.submission_type
    WHEN 'park' THEN 'New park submission'
    WHEN 'ride' THEN 'New ride submission'
    WHEN 'company' THEN 'New company submission'
    WHEN 'ride_model' THEN 'New ride model submission'
    WHEN 'photo' THEN 'New photo submission'
    ELSE 'New submission'
  END;
  
  -- Check if this submission has photos
  has_photos := EXISTS (
    SELECT 1 FROM photo_submissions ps
    WHERE ps.submission_id = NEW.id
  );
  
  -- Count submission items
  SELECT COALESCE(COUNT(*), 0)::integer INTO item_count
  FROM submission_items
  WHERE submission_id = NEW.id;
  
  -- Get base URL from settings
  SELECT setting_value::text INTO base_url 
  FROM admin_settings 
  WHERE setting_key = 'supabase_api_url';
  
  base_url := trim(both '"' from base_url);
  
  IF base_url IS NULL THEN
    base_url := 'https://api.thrillwiki.com';
  END IF;
  
  edge_function_url := base_url || '/functions/v1/notify-moderators-submission';
  
  -- Call the edge function via pg_net
  PERFORM public.pg_net.http_post(
    edge_function_url,
    jsonb_build_object(
      'submission_id', NEW.id,
      'submission_type', NEW.submission_type,
      'submitter_name', COALESCE(submitter_profile.display_name, submitter_profile.username, 'Unknown'),
      'action', 'create',
      'content_preview', content_preview,
      'submitted_at', NEW.created_at,
      'has_photos', has_photos,
      'item_count', item_count,
      'is_escalated', false
    )::text,
    'application/json'
  );
  
  RETURN NEW;
EXCEPTION
  WHEN OTHERS THEN
    -- Log error but don't fail the submission
    RAISE NOTICE 'Failed to notify moderators: %', SQLERRM;
    RETURN NEW;
END;
$function$;