-- BGP EVPN RIB table (roadmap E5)
--
-- The OpenBMP collector already decodes EVPN and emits the
-- 'openbmp.parsed.evpn' Kafka topic, but the stock psql-app consumer never
-- subscribes to it and the base schema has no table for it. This table is
-- the landing zone; a dedicated consumer (obmp-evpn-consumer, separate)
-- subscribes to the topic and writes here.
--
-- Mirrors l3vpn_rib conventions. route_type is derived by the consumer from
-- which fields are populated (the parsed EVPN message has no explicit type),
-- so it is nullable.
CREATE TABLE IF NOT EXISTS evpn_rib (
    hash_id                uuid NOT NULL,
    base_attr_hash_id      uuid,
    peer_hash_id           uuid NOT NULL,
    rd                     varchar(128) NOT NULL,
    rd_type                smallint,
    route_type             smallint,                 -- EVPN route type 1..5
    origin_as              bigint,
    eth_segment_id         varchar(255),             -- ESI
    eth_tag_id             bigint,
    mac                    macaddr,
    mac_len                smallint,
    ip                     inet,
    ip_len                 smallint,
    orig_router_ip         inet,
    mpls_label1            bigint,                   -- VXLAN VNI when encap = vxlan
    mpls_label2            bigint,
    ext_community_list     varchar(50)[],            -- route-targets
    path_id                bigint,
    timestamp              timestamp(6) without time zone NOT NULL DEFAULT (now() AT TIME ZONE 'utc'),
    first_added_timestamp  timestamp(6) without time zone NOT NULL DEFAULT (now() AT TIME ZONE 'utc'),
    iswithdrawn            boolean NOT NULL DEFAULT false,
    isprepolicy            boolean NOT NULL DEFAULT true,
    isadjribin             boolean NOT NULL DEFAULT true,
    PRIMARY KEY (peer_hash_id, hash_id)
);
CREATE INDEX IF NOT EXISTS evpn_rib_hash_id_idx    ON evpn_rib (hash_id);
CREATE INDEX IF NOT EXISTS evpn_rib_base_attr_idx  ON evpn_rib (base_attr_hash_id);
CREATE INDEX IF NOT EXISTS evpn_rib_rd_idx         ON evpn_rib (rd);
CREATE INDEX IF NOT EXISTS evpn_rib_route_type_idx ON evpn_rib (route_type);
CREATE INDEX IF NOT EXISTS evpn_rib_mac_idx        ON evpn_rib (mac);
CREATE INDEX IF NOT EXISTS evpn_rib_extcomm_idx    ON evpn_rib USING gin (ext_community_list);
CREATE INDEX IF NOT EXISTS evpn_rib_timestamp_idx  ON evpn_rib ("timestamp");
