-- Trading workload SQL for pgbench
-- 40% INSERT, 30% SELECT, 20% UPDATE, 10% Complex queries

\set account_id 'test_account_' :client_id
\set venue 'test_venue'
\set symbol random(1, 3)

-- Map random number to symbol
\if :symbol = 1
    \set symbol_str 'BTC/USD'
\elif :symbol = 2
    \set symbol_str 'ETH/USD'
\else
    \set symbol_str 'SOL/USD'
\endif

\set operation random(1, 10)

-- 40% INSERT (operations 1-4)
\if :operation <= 4
INSERT INTO orders (account_id, symbol, side, order_type, quantity, limit_price, venue, created_at, updated_at)
VALUES (:'account_id', :'symbol_str', 'buy', 'limit', 100000000, 5000000000000, :'venue',
        EXTRACT(EPOCH FROM NOW()) * 1000000000, EXTRACT(EPOCH FROM NOW()) * 1000000000);

-- 30% SELECT (operations 5-7)
\elif :operation <= 7
SELECT id, status, quantity, filled_quantity
FROM orders
WHERE symbol = :'symbol_str'
ORDER BY created_at DESC
LIMIT 10;

-- 20% UPDATE (operations 8-9)
\elif :operation <= 9
UPDATE orders
SET status = 'partially_filled',
    filled_quantity = filled_quantity + 10000000,
    updated_at = EXTRACT(EPOCH FROM NOW()) * 1000000000
WHERE id = (
    SELECT id
    FROM orders
    WHERE status = 'pending'
    AND symbol = :'symbol_str'
    LIMIT 1
);

-- 10% Complex query (operation 10)
\else
SELECT symbol,
       COUNT(*) as order_count,
       SUM(quantity) as total_quantity,
       AVG(limit_price) as avg_price,
       COUNT(DISTINCT account_id) as unique_accounts
FROM orders
WHERE created_at > EXTRACT(EPOCH FROM (NOW() - INTERVAL '1 hour')) * 1000000000
GROUP BY symbol
ORDER BY order_count DESC;

\endif
