-- Fix get_submission_items_with_entities to use correct column names
-- The submission_items table has approved_entity_id and rejection_reason, not approved_by/rejected_by

DROP FUNCTION IF EXISTS get_submission_items_with_entities(uuid);

CREATE OR REPLACE FUNCTION get_submission_items_with_entities(p_submission_id uuid)
RETURNS TABLE (
  id uuid,
  submission_id uuid,
  item_type text,
  action_type text,
  status text,
  order_index integer,
  depends_on uuid,
  park_submission_id uuid,
  ride_submission_id uuid,
  company_submission_id uuid,
  photo_submission_id uuid,
  ride_model_submission_id uuid,
  timeline_event_submission_id uuid,
  approved_entity_id uuid,
  rejection_reason text,
  is_test_data boolean,
  created_at timestamptz,
  updated_at timestamptz,
  entity_data jsonb
)
SECURITY DEFINER
SET search_path TO 'public'
LANGUAGE plpgsql
AS $$
BEGIN
  RETURN QUERY
  SELECT 
    si.id,
    si.submission_id,
    si.item_type,
    si.action_type,
    si.status,
    si.order_index,
    si.depends_on,
    si.park_submission_id,
    si.ride_submission_id,
    si.company_submission_id,
    si.photo_submission_id,
    si.ride_model_submission_id,
    si.timeline_event_submission_id,
    si.approved_entity_id,
    si.rejection_reason,
    si.is_test_data,
    si.created_at,
    si.updated_at,
    -- Join entity data based on item_type
    CASE
      WHEN si.item_type = 'park' THEN
        (SELECT to_jsonb(ps.*) FROM park_submissions ps WHERE ps.id = si.park_submission_id)
      WHEN si.item_type = 'ride' THEN
        (SELECT to_jsonb(rs.*) FROM ride_submissions rs WHERE rs.id = si.ride_submission_id)
      WHEN si.item_type IN ('manufacturer', 'operator', 'designer', 'property_owner') THEN
        (SELECT to_jsonb(cs.*) FROM company_submissions cs WHERE cs.id = si.company_submission_id)
      WHEN si.item_type IN ('photo', 'photo_edit', 'photo_delete') THEN
        (SELECT to_jsonb(phs.*) FROM photo_submissions phs WHERE phs.id = si.photo_submission_id)
      WHEN si.item_type = 'ride_model' THEN
        (SELECT to_jsonb(rms.*) FROM ride_model_submissions rms WHERE rms.id = si.ride_model_submission_id)
      ELSE NULL
    END AS entity_data
  FROM submission_items si
  WHERE si.submission_id = p_submission_id
  ORDER BY si.order_index;
END;
$$;

COMMENT ON FUNCTION get_submission_items_with_entities IS 
'Fetch submission items with their entity data in a single query. Uses SECURITY DEFINER to access submission tables with proper RLS context.';

GRANT EXECUTE ON FUNCTION get_submission_items_with_entities(uuid) TO authenticated;