CREATE OR REPLACE FUNCTION apply_group_consumed_delta()
RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE
  v_chain_id bigint;
  v_maker    varchar(42);
  v_group    varchar(66);
  v_delta    numeric;
BEGIN
  IF TG_OP = 'INSERT' THEN
    v_chain_id := NEW.chain_id;
    v_maker    := NEW.maker;
    -- group needs to be quoted because it's a reserved word
    v_group    := NEW."group";
    v_delta    := NEW.amount;

  ELSIF TG_OP = 'UPDATE' THEN
    -- if group keys changed, subtract from old & add to new
    IF NEW.chain_id = OLD.chain_id AND NEW.maker = OLD.maker AND NEW."group" = OLD."group" THEN
      v_chain_id := NEW.chain_id; v_maker := NEW.maker; v_group := NEW."group";
      v_delta := NEW.amount - OLD.amount;
    ELSE
      -- move: undo old...
      UPDATE "router_v1.7"."groups" g
      SET consumed = (g.consumed - OLD.amount)
      WHERE g.chain_id = OLD.chain_id AND g.maker = OLD.maker AND g."group" = OLD."group";

      -- ...apply new
      UPDATE "router_v1.7"."groups" g
      SET consumed = (g.consumed + NEW.amount)
      WHERE g.chain_id = NEW.chain_id AND g.maker = NEW.maker AND g."group" = NEW."group";

      RETURN NEW;
    END IF;

  ELSIF TG_OP = 'DELETE' THEN
    v_chain_id := OLD.chain_id;
    v_maker    := OLD.maker;
    v_group    := OLD."group";
    v_delta    := -OLD.amount;

  ELSE
    RAISE EXCEPTION 'Unsupported TG_OP %', TG_OP;
  END IF;

  UPDATE "router_v1.7"."groups" g
  SET consumed = (g.consumed + v_delta)
  WHERE g.chain_id = v_chain_id AND g.maker = v_maker AND g."group" = v_group;

  RETURN COALESCE(NEW, OLD);
END;
$$; --> statement-breakpoint

-- trigger names can’t be schema-qualified
DROP TRIGGER IF EXISTS trg_consumed_events ON "router_v1.7"."consumed_events"; --> statement-breakpoint

CREATE TRIGGER trg_consumed_events
AFTER INSERT OR UPDATE OR DELETE ON "router_v1.7"."consumed_events"
FOR EACH ROW EXECUTE FUNCTION apply_group_consumed_delta();
