-- Create Broadcast Authorization Policy
CREATE POLICY "Moderators can receive broadcasts"
ON "realtime"."messages"
FOR SELECT
TO authenticated
USING (public.check_realtime_access());

-- Create Trigger Functions for Broadcast
CREATE OR REPLACE FUNCTION public.broadcast_content_submission_changes()
RETURNS trigger
SECURITY DEFINER
LANGUAGE plpgsql
AS $$
BEGIN
  PERFORM realtime.broadcast_changes(
    'moderation:content_submissions',
    TG_OP,
    TG_OP,
    TG_TABLE_NAME,
    TG_TABLE_SCHEMA,
    NEW,
    OLD
  );
  RETURN NULL;
END;
$$;

CREATE OR REPLACE FUNCTION public.broadcast_submission_item_changes()
RETURNS trigger
SECURITY DEFINER
LANGUAGE plpgsql
AS $$
BEGIN
  PERFORM realtime.broadcast_changes(
    'moderation:submission_items',
    TG_OP,
    TG_OP,
    TG_TABLE_NAME,
    TG_TABLE_SCHEMA,
    NEW,
    OLD
  );
  RETURN NULL;
END;
$$;

CREATE OR REPLACE FUNCTION public.broadcast_report_changes()
RETURNS trigger
SECURITY DEFINER
LANGUAGE plpgsql
AS $$
BEGIN
  PERFORM realtime.broadcast_changes(
    'moderation:reports',
    TG_OP,
    TG_OP,
    TG_TABLE_NAME,
    TG_TABLE_SCHEMA,
    NEW,
    OLD
  );
  RETURN NULL;
END;
$$;

CREATE OR REPLACE FUNCTION public.broadcast_review_changes()
RETURNS trigger
SECURITY DEFINER
LANGUAGE plpgsql
AS $$
BEGIN
  PERFORM realtime.broadcast_changes(
    'moderation:reviews',
    TG_OP,
    TG_OP,
    TG_TABLE_NAME,
    TG_TABLE_SCHEMA,
    NEW,
    OLD
  );
  RETURN NULL;
END;
$$;

-- Create Triggers
CREATE TRIGGER broadcast_content_submission_changes
AFTER INSERT OR UPDATE OR DELETE
ON public.content_submissions
FOR EACH ROW
EXECUTE FUNCTION public.broadcast_content_submission_changes();

CREATE TRIGGER broadcast_submission_item_changes
AFTER INSERT OR UPDATE OR DELETE
ON public.submission_items
FOR EACH ROW
EXECUTE FUNCTION public.broadcast_submission_item_changes();

CREATE TRIGGER broadcast_report_changes
AFTER INSERT OR UPDATE OR DELETE
ON public.reports
FOR EACH ROW
EXECUTE FUNCTION public.broadcast_report_changes();

CREATE TRIGGER broadcast_review_changes
AFTER INSERT OR UPDATE OR DELETE
ON public.reviews
FOR EACH ROW
EXECUTE FUNCTION public.broadcast_review_changes();