-- Migration: Relay Account Whitelist + Trust-Gated Access (#47)
-- Adds the relay_accounts and relay_event_queue tables that back the
-- whitelist-gated Nostr relay policy.

-- ── relay_accounts ────────────────────────────────────────────────────────────
-- One row per pubkey that has been explicitly registered with the relay.
-- Absence = "none" (default deny). FK to nostr_identities.

CREATE TABLE IF NOT EXISTS relay_accounts (
  pubkey       TEXT PRIMARY KEY REFERENCES nostr_identities(pubkey) ON DELETE CASCADE,
  access_level TEXT NOT NULL DEFAULT 'none',   -- 'none' | 'read' | 'write'
  granted_by   TEXT NOT NULL DEFAULT 'manual', -- 'manual' | 'auto-tier' | 'manual-revoked'
  granted_at   TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  revoked_at   TIMESTAMPTZ,
  notes        TEXT
);

-- ── relay_event_queue ─────────────────────────────────────────────────────────
-- Holds events submitted by whitelisted non-elite accounts pending moderation.
-- Elite accounts bypass this table; their events are injected directly into strfry.

CREATE TABLE IF NOT EXISTS relay_event_queue (
  event_id      TEXT PRIMARY KEY,
  pubkey        TEXT NOT NULL REFERENCES nostr_identities(pubkey) ON DELETE CASCADE,
  kind          INTEGER NOT NULL,
  raw_event     TEXT NOT NULL,
  status        TEXT NOT NULL DEFAULT 'pending', -- 'pending' | 'approved' | 'rejected' | 'auto_approved' | 'flagged'
  reviewed_by   TEXT,                            -- 'timmy_ai' | 'admin'
  review_reason TEXT,
  created_at    TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  decided_at    TIMESTAMPTZ
);

CREATE INDEX IF NOT EXISTS idx_relay_event_queue_pubkey
  ON relay_event_queue(pubkey);

CREATE INDEX IF NOT EXISTS idx_relay_event_queue_status
  ON relay_event_queue(status);
