-- Fix create_submission_with_items to remove non-existent 'content' column
-- The content column was removed during architectural cleanup but the RPC wasn't updated

CREATE OR REPLACE FUNCTION public.create_submission_with_items(
  p_user_id uuid, 
  p_submission_type text, 
  p_content jsonb,  -- Keep parameter for backward compatibility, but don't use it
  p_items jsonb[]
)
RETURNS uuid
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public'
AS $$
DECLARE
  v_submission_id UUID;
  v_item JSONB;
BEGIN
  -- Insert submission WITHOUT content column (column no longer exists)
  INSERT INTO content_submissions (user_id, submission_type, status, approval_mode)
  VALUES (p_user_id, p_submission_type, 'pending', 'full')
  RETURNING id INTO v_submission_id;
  
  -- Validate we have at least one item
  IF array_length(p_items, 1) IS NULL OR array_length(p_items, 1) = 0 THEN
    RAISE EXCEPTION 'Cannot create submission without items';
  END IF;
  
  -- Insert all items atomically (fails entire transaction if any fail)
  FOREACH v_item IN ARRAY p_items
  LOOP
    INSERT INTO submission_items (
      submission_id,
      item_type,
      action_type,
      park_submission_id,
      ride_submission_id,
      company_submission_id,
      photo_submission_id,
      ride_model_submission_id,
      timeline_event_submission_id,
      status,
      order_index,
      depends_on
    ) VALUES (
      v_submission_id,
      (v_item->>'item_type')::TEXT,
      (v_item->>'action_type')::TEXT,
      (v_item->>'park_submission_id')::UUID,
      (v_item->>'ride_submission_id')::UUID,
      (v_item->>'company_submission_id')::UUID,
      (v_item->>'photo_submission_id')::UUID,
      (v_item->>'ride_model_submission_id')::UUID,
      (v_item->>'timeline_event_submission_id')::UUID,
      'pending',
      COALESCE((v_item->>'order_index')::INTEGER, 0),
      (v_item->>'depends_on')::UUID
    );
  END LOOP;
  
  RETURN v_submission_id;
END;
$$;