-- Add notify_pbi_change() function and pbis_notify_change trigger so that
-- INSERT/UPDATE/DELETE on pbis emits a pg_notify on 'scrum4me_changes'.
-- Payload field names match BacklogPbi directly (no client-side rename needed).

CREATE OR REPLACE FUNCTION notify_pbi_change() RETURNS trigger AS $$
DECLARE
  rec record;
  payload jsonb;
BEGIN
  IF TG_OP = 'DELETE' THEN
    rec := OLD;
  ELSE
    rec := NEW;
  END IF;

  payload := jsonb_build_object(
    'op', CASE TG_OP
            WHEN 'INSERT' THEN 'I'
            WHEN 'UPDATE' THEN 'U'
            WHEN 'DELETE' THEN 'D'
          END,
    'entity', 'pbi',
    'id', rec.id,
    'product_id', rec.product_id,
    'title', rec.title,
    'code', rec.code,
    'priority', rec.priority,
    'status', rec.status,
    'sort_order', rec.sort_order,
    'created_at', rec.created_at
  );

  IF TG_OP = 'UPDATE' THEN
    payload := payload || jsonb_build_object(
      'changed_fields',
      COALESCE((
        SELECT jsonb_agg(n.key)
        FROM jsonb_each(to_jsonb(NEW)) n
        JOIN jsonb_each(to_jsonb(OLD)) o USING (key)
        WHERE n.value IS DISTINCT FROM o.value
      ), '[]'::jsonb)
    );
  END IF;

  PERFORM pg_notify('scrum4me_changes', payload::text);
  RETURN rec;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS pbis_notify_change ON pbis;
CREATE TRIGGER pbis_notify_change
  AFTER INSERT OR UPDATE OR DELETE ON pbis
  FOR EACH ROW EXECUTE FUNCTION notify_pbi_change();
