-- Feature 1: BGP Hijack Alerting + Webhooks
-- Tables for persistent hijack event storage, webhook subscriptions, and delivery audit log

BEGIN;

-- Hijack Events Table
CREATE TABLE IF NOT EXISTS hijack_events (
  id SERIAL PRIMARY KEY,
  asn INTEGER NOT NULL,
  prefix CIDR NOT NULL,
  detected_at TIMESTAMP NOT NULL DEFAULT NOW(),
  expected_asn INTEGER NOT NULL,
  detected_asns INTEGER[] NOT NULL,
  hijack_type VARCHAR(50),
  severity VARCHAR(20),
  description TEXT NOT NULL,
  details JSONB NOT NULL,
  resolved BOOLEAN DEFAULT FALSE,
  resolved_at TIMESTAMP,
  created_at TIMESTAMP NOT NULL DEFAULT NOW(),
  UNIQUE(asn, prefix, detected_at)
);

CREATE INDEX IF NOT EXISTS idx_hijack_events_asn ON hijack_events(asn);
CREATE INDEX IF NOT EXISTS idx_hijack_events_detected ON hijack_events(detected_at DESC);
CREATE INDEX IF NOT EXISTS idx_hijack_events_resolved ON hijack_events(resolved);

-- Webhook Subscriptions Table
CREATE TABLE IF NOT EXISTS webhook_subscriptions (
  id SERIAL PRIMARY KEY,
  asn INTEGER NOT NULL,
  endpoint_url VARCHAR(2048) NOT NULL,
  secret_key VARCHAR(256) NOT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT NOW(),
  last_triggered_at TIMESTAMP,
  failure_count INTEGER DEFAULT 0,
  active BOOLEAN DEFAULT TRUE,
  max_retries INTEGER DEFAULT 3,
  timeout_ms INTEGER DEFAULT 10000,
  metadata JSONB DEFAULT '{}',
  UNIQUE(asn, endpoint_url)
);

CREATE INDEX IF NOT EXISTS idx_webhooks_asn ON webhook_subscriptions(asn);
CREATE INDEX IF NOT EXISTS idx_webhooks_active ON webhook_subscriptions(active);

-- Webhook Delivery Audit Log
CREATE TABLE IF NOT EXISTS webhook_deliveries (
  id SERIAL PRIMARY KEY,
  subscription_id INTEGER NOT NULL REFERENCES webhook_subscriptions(id) ON DELETE CASCADE,
  event_id INTEGER NOT NULL REFERENCES hijack_events(id) ON DELETE CASCADE,
  attempt_number INTEGER NOT NULL,
  sent_at TIMESTAMP NOT NULL DEFAULT NOW(),
  response_status INTEGER,
  response_body TEXT,
  error_message TEXT,
  next_retry_at TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_deliveries_subscription ON webhook_deliveries(subscription_id);
CREATE INDEX IF NOT EXISTS idx_deliveries_event ON webhook_deliveries(event_id);
CREATE INDEX IF NOT EXISTS idx_deliveries_retry ON webhook_deliveries(next_retry_at) WHERE next_retry_at IS NOT NULL;

COMMIT;
