-- Migration: Track auth/operator tables for shared Blockscout database
-- Description: Creates only the explorer-owned auth/operator tables that do not
-- conflict with Blockscout's existing addresses/token_transfers schema.

CREATE TABLE IF NOT EXISTS operator_events (
    id SERIAL PRIMARY KEY,
    event_type VARCHAR(100) NOT NULL,
    chain_id INTEGER,
    operator_address VARCHAR(42) NOT NULL,
    target_resource VARCHAR(200),
    action VARCHAR(100) NOT NULL,
    details JSONB,
    ip_address INET,
    user_agent TEXT,
    timestamp TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_operator_events_type ON operator_events(event_type);
CREATE INDEX IF NOT EXISTS idx_operator_events_operator ON operator_events(operator_address);
CREATE INDEX IF NOT EXISTS idx_operator_events_timestamp ON operator_events(timestamp);
CREATE INDEX IF NOT EXISTS idx_operator_events_chain ON operator_events(chain_id);

CREATE TABLE IF NOT EXISTS operator_ip_whitelist (
    id SERIAL PRIMARY KEY,
    operator_address VARCHAR(42) NOT NULL,
    ip_address INET NOT NULL,
    description TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    UNIQUE(operator_address, ip_address)
);

CREATE INDEX IF NOT EXISTS idx_operator_whitelist_operator ON operator_ip_whitelist(operator_address);
CREATE INDEX IF NOT EXISTS idx_operator_whitelist_ip ON operator_ip_whitelist(ip_address);

CREATE TABLE IF NOT EXISTS operator_roles (
    id SERIAL PRIMARY KEY,
    address VARCHAR(42) NOT NULL UNIQUE,
    track_level INTEGER NOT NULL DEFAULT 4,
    roles TEXT[],
    approved BOOLEAN DEFAULT FALSE,
    approved_by VARCHAR(42),
    approved_at TIMESTAMP WITH TIME ZONE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_operator_roles_address ON operator_roles(address);
CREATE INDEX IF NOT EXISTS idx_operator_roles_approved ON operator_roles(approved);

CREATE TABLE IF NOT EXISTS wallet_nonces (
    id SERIAL PRIMARY KEY,
    address VARCHAR(42) NOT NULL UNIQUE,
    nonce VARCHAR(64) NOT NULL,
    expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_wallet_nonces_address ON wallet_nonces(address);
CREATE INDEX IF NOT EXISTS idx_wallet_nonces_expires ON wallet_nonces(expires_at);
