-- Peer auto-discovery pending / rejected / approved records.

CREATE TABLE IF NOT EXISTS bgp_peer_discovery (
    id               UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id        UUID NOT NULL REFERENCES tenant (id) ON DELETE CASCADE,
    speaker_id       UUID REFERENCES bgp_speaker (id) ON DELETE SET NULL,
    neighbor_id      TEXT NOT NULL DEFAULT '',
    neighbor         INET NOT NULL,
    remote_asn       BIGINT NOT NULL DEFAULT 0,
    protocol_name    TEXT NOT NULL DEFAULT '',
    session_state    TEXT NOT NULL DEFAULT '',
    status           TEXT NOT NULL DEFAULT 'pending',
    first_seen_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    last_seen_at     TIMESTAMPTZ NOT NULL DEFAULT now(),
    approved_peer_id UUID REFERENCES bgp_peer (id) ON DELETE SET NULL,
    created_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
    CONSTRAINT bgp_peer_discovery_status_chk CHECK (status IN ('pending', 'approved', 'rejected'))
);

CREATE INDEX IF NOT EXISTS idx_bgp_peer_discovery_tenant_status
    ON bgp_peer_discovery (tenant_id, status);

CREATE UNIQUE INDEX IF NOT EXISTS idx_bgp_peer_discovery_tenant_neighbor_id
    ON bgp_peer_discovery (tenant_id, neighbor_id)
    WHERE neighbor_id <> '';

CREATE UNIQUE INDEX IF NOT EXISTS idx_bgp_peer_discovery_tenant_neighbor_asn
    ON bgp_peer_discovery (tenant_id, neighbor, remote_asn)
    WHERE neighbor_id = '';
