-- Simple Master Schema for Symbol Resolution
-- Connect to trading_bot database
\c trading_bot;

-- Exchanges Table
CREATE TABLE IF NOT EXISTS exchanges (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    code VARCHAR(10) UNIQUE NOT NULL,           -- NASDAQ, NYSE, TSX, etc.
    name VARCHAR(255) NOT NULL,                 -- Full exchange name
    country CHAR(2) NOT NULL,                   -- US, CA, GB
    currency CHAR(3) NOT NULL DEFAULT 'USD',    -- USD, CAD, GBP
    is_active BOOLEAN DEFAULT true,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);

-- Symbols Table
CREATE TABLE IF NOT EXISTS symbols (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    symbol VARCHAR(20) NOT NULL,                -- AAPL, SHOP, etc.
    exchange_id UUID REFERENCES exchanges(id),
    company_name VARCHAR(255),
    sector VARCHAR(100),
    country CHAR(2),
    currency CHAR(3),
    is_active BOOLEAN DEFAULT true,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW(),
    UNIQUE(symbol, exchange_id)
);

-- Provider Symbol Mappings (How each provider refers to our symbols)
CREATE TABLE IF NOT EXISTS provider_mappings (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    symbol_id UUID REFERENCES symbols(id),
    provider VARCHAR(50) NOT NULL,              -- 'qm', 'yahoo', 'ib', etc.
    provider_symbol VARCHAR(100) NOT NULL,      -- How provider names it: "AAPL:NASDAQ", "SHOP.TO"
    provider_exchange VARCHAR(50),              -- Provider's exchange code
    confidence DECIMAL(3,2) DEFAULT 1.0,       -- 0.0 to 1.0 matching confidence
    verified BOOLEAN DEFAULT false,             -- Manually verified flag
    last_seen TIMESTAMP DEFAULT NOW(),
    created_at TIMESTAMP DEFAULT NOW(),
    UNIQUE(provider, provider_symbol)
);

-- Simple sync tracking table
CREATE TABLE IF NOT EXISTS sync_status (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    provider VARCHAR(50) NOT NULL,
    data_type VARCHAR(50) NOT NULL,             -- 'symbols', 'exchanges'
    last_sync_at TIMESTAMP,
    last_sync_count INTEGER DEFAULT 0,
    sync_errors TEXT,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW(),
    UNIQUE(provider, data_type)
);

-- Create basic indexes
CREATE INDEX IF NOT EXISTS idx_symbols_symbol ON symbols(symbol);
CREATE INDEX IF NOT EXISTS idx_symbols_exchange ON symbols(exchange_id);
CREATE INDEX IF NOT EXISTS idx_provider_mappings_provider ON provider_mappings(provider, provider_symbol);
CREATE INDEX IF NOT EXISTS idx_provider_mappings_symbol ON provider_mappings(symbol_id);