-- Fix timeline event display in moderation queue
-- Add timeline_event_submissions to the get_submission_items_with_entities function

-- Drop and recreate the function with timeline events support
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
)
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
STABLE
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)
      WHEN si.item_type IN ('milestone', 'timeline_event') THEN
        (SELECT to_jsonb(tes.*) FROM timeline_event_submissions tes WHERE tes.id = si.timeline_event_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. Now includes timeline_event_submissions.';

GRANT EXECUTE ON FUNCTION get_submission_items_with_entities(uuid) TO authenticated;