-- =============================================================================
-- Interactive Brokers Simple Schema Setup
-- =============================================================================

-- Create dedicated schema for IB data
CREATE SCHEMA IF NOT EXISTS ib_data;

-- =============================================================================
-- Simple Exchanges Table
-- =============================================================================

CREATE TABLE IF NOT EXISTS ib_data.exchanges (
    id SERIAL PRIMARY KEY,
    exchange_code VARCHAR(20) NOT NULL UNIQUE,
    exchange_name TEXT NOT NULL,
    country VARCHAR(100),
    region VARCHAR(50),
    country_code VARCHAR(3),
    assets TEXT,
    is_active BOOLEAN DEFAULT true,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Create indexes for performance
CREATE INDEX IF NOT EXISTS idx_exchanges_code ON ib_data.exchanges(exchange_code);
CREATE INDEX IF NOT EXISTS idx_exchanges_country ON ib_data.exchanges(country_code);
CREATE INDEX IF NOT EXISTS idx_exchanges_region ON ib_data.exchanges(region);
CREATE INDEX IF NOT EXISTS idx_exchanges_active ON ib_data.exchanges(is_active);

-- =============================================================================
-- Permissions
-- =============================================================================

-- Grant usage on schema
GRANT USAGE ON SCHEMA ib_data TO PUBLIC;

-- Grant permissions on tables
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA ib_data TO PUBLIC;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ib_data TO PUBLIC;

-- Set default permissions for future tables
ALTER DEFAULT PRIVILEGES IN SCHEMA ib_data GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO PUBLIC;
ALTER DEFAULT PRIVILEGES IN SCHEMA ib_data GRANT USAGE, SELECT ON SEQUENCES TO PUBLIC;

-- =============================================================================
-- Comments
-- =============================================================================

COMMENT ON SCHEMA ib_data IS 'Interactive Brokers market data schema (simplified)';
COMMENT ON TABLE ib_data.exchanges IS 'Trading exchanges from Interactive Brokers';
