-- ASPA Adoption Tracker Tables

-- Daily adoption snapshot
CREATE TABLE IF NOT EXISTS aspa_adoption_history (
  id SERIAL PRIMARY KEY,
  sample_date DATE NOT NULL UNIQUE,
  sampled_at TIMESTAMP NOT NULL DEFAULT NOW(),
  total_asns_sampled INTEGER NOT NULL,
  asns_with_aspa INTEGER NOT NULL,
  coverage_percentage NUMERIC(5,2) NOT NULL,
  adoption_rate_change_percent NUMERIC(5,2),
  top_adopters JSONB NOT NULL DEFAULT '[]',
  regions JSONB NOT NULL DEFAULT '[]',
  sample_method VARCHAR(100),
  metadata JSONB DEFAULT '{}',
  created_at TIMESTAMP NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_aspa_date ON aspa_adoption_history(sample_date DESC);
CREATE INDEX IF NOT EXISTS idx_aspa_coverage ON aspa_adoption_history(coverage_percentage);

-- Regional breakdown
CREATE TABLE IF NOT EXISTS aspa_adoption_by_region (
  id SERIAL PRIMARY KEY,
  sample_date DATE NOT NULL,
  region VARCHAR(100) NOT NULL,
  total_asns INTEGER NOT NULL,
  asns_with_aspa INTEGER NOT NULL,
  coverage_percentage NUMERIC(5,2) NOT NULL,
  top_networks JSONB DEFAULT '[]',
  created_at TIMESTAMP NOT NULL DEFAULT NOW(),
  UNIQUE(sample_date, region)
);

CREATE INDEX IF NOT EXISTS idx_aspa_region_date ON aspa_adoption_by_region(region, sample_date DESC);
CREATE INDEX IF NOT EXISTS idx_aspa_region_coverage ON aspa_adoption_by_region(coverage_percentage);

-- IXP-level adoption
CREATE TABLE IF NOT EXISTS aspa_adoption_by_ixp (
  id SERIAL PRIMARY KEY,
  sample_date DATE NOT NULL,
  ixp_id INTEGER NOT NULL,
  ixp_name VARCHAR(255) NOT NULL,
  participant_count INTEGER NOT NULL,
  participants_with_aspa INTEGER NOT NULL,
  coverage_percentage NUMERIC(5,2) NOT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT NOW(),
  UNIQUE(sample_date, ixp_id)
);

CREATE INDEX IF NOT EXISTS idx_aspa_ixp_date ON aspa_adoption_by_ixp(ixp_id, sample_date DESC);
CREATE INDEX IF NOT EXISTS idx_aspa_ixp_coverage ON aspa_adoption_by_ixp(coverage_percentage);
