-- PostgreSQL Performance Test Script
-- Tests connection pool performance and throughput

\timing on

-- Test 1: Basic query performance
SELECT 'Test 1: Basic query performance' as test;
SELECT COUNT(*) FROM config_settings;

-- Test 2: Temporary table creation and inserts
SELECT 'Test 2: Creating temporary test table' as test;
CREATE TEMP TABLE perf_test (
    id SERIAL PRIMARY KEY,
    trade_id VARCHAR(50),
    symbol VARCHAR(10),
    price DECIMAL(18,8),
    quantity DECIMAL(18,8),
    timestamp TIMESTAMPTZ DEFAULT NOW()
);

-- Test 3: Bulk insert performance (1000 records)
SELECT 'Test 3: Bulk insert 1000 records' as test;
INSERT INTO perf_test (trade_id, symbol, price, quantity)
SELECT
    'TRADE_' || generate_series || '_' || extract(epoch from now()),
    CASE (random() * 5)::int
        WHEN 0 THEN 'BTC/USD'
        WHEN 1 THEN 'ETH/USD'
        WHEN 2 THEN 'AAPL'
        WHEN 3 THEN 'GOOGL'
        ELSE 'MSFT'
    END,
    (random() * 1000)::decimal(18,8),
    (random() * 100)::decimal(18,8)
FROM generate_series(1, 1000);

-- Test 4: Query performance on test data
SELECT 'Test 4: Query performance (aggregation)' as test;
SELECT symbol, COUNT(*) as trade_count, AVG(price) as avg_price
FROM perf_test
GROUP BY symbol;

-- Test 5: Index creation and query optimization
SELECT 'Test 5: Creating index' as test;
CREATE INDEX idx_perf_test_symbol_timestamp ON perf_test(symbol, timestamp DESC);

-- Test 6: Indexed query performance
SELECT 'Test 6: Indexed query performance' as test;
SELECT * FROM perf_test WHERE symbol = 'BTC/USD' ORDER BY timestamp DESC LIMIT 100;

-- Test 7: Transaction performance (1000 individual inserts)
SELECT 'Test 7: Transaction performance (1000 individual inserts)' as test;
BEGIN;
DO $$
DECLARE
    i INT;
BEGIN
    FOR i IN 1..1000 LOOP
        INSERT INTO perf_test (trade_id, symbol, price, quantity)
        VALUES (
            'TRADE_TX_' || i || '_' || extract(epoch from now()),
            CASE (random() * 5)::int
                WHEN 0 THEN 'BTC/USD'
                WHEN 1 THEN 'ETH/USD'
                WHEN 2 THEN 'AAPL'
                WHEN 3 THEN 'GOOGL'
                ELSE 'MSFT'
            END,
            (random() * 1000)::decimal(18,8),
            (random() * 100)::decimal(18,8)
        );
    END LOOP;
END $$;
COMMIT;

-- Test 8: Final statistics
SELECT 'Test 8: Final statistics' as test;
SELECT COUNT(*) as total_records FROM perf_test;

-- Test 9: Connection and pool statistics
SELECT 'Test 9: Database statistics' as test;
SELECT
    numbackends as active_connections,
    xact_commit as committed_transactions,
    xact_rollback as rolled_back_transactions,
    blks_read as blocks_read,
    blks_hit as blocks_hit,
    tup_returned as tuples_returned,
    tup_fetched as tuples_fetched,
    tup_inserted as tuples_inserted
FROM pg_stat_database
WHERE datname = 'foxhunt';

SELECT 'Performance test completed!' as status;
