-- ============================================================
-- Migration 009: Tenant RLS Hardening for Orders + Trade History
-- Date: 2026-02-16
-- Purpose: Enforce user-level row isolation for lifecycle tables.
-- ============================================================

-- ORDERS table policies
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;

DROP POLICY IF EXISTS "Users can read own orders" ON orders;
CREATE POLICY "Users can read own orders" ON orders
    FOR SELECT
    USING (auth.uid() = user_id);

DROP POLICY IF EXISTS "Users can insert own orders" ON orders;
CREATE POLICY "Users can insert own orders" ON orders
    FOR INSERT
    WITH CHECK (auth.uid() = user_id);

DROP POLICY IF EXISTS "Users can update own orders" ON orders;
CREATE POLICY "Users can update own orders" ON orders
    FOR UPDATE
    USING (auth.uid() = user_id)
    WITH CHECK (auth.uid() = user_id);

-- TRADE_HISTORY table policies
ALTER TABLE trade_history ENABLE ROW LEVEL SECURITY;

DROP POLICY IF EXISTS "Users can read own trade history" ON trade_history;
CREATE POLICY "Users can read own trade history" ON trade_history
    FOR SELECT
    USING (auth.uid() = user_id);

DROP POLICY IF EXISTS "Users can insert own trade history" ON trade_history;
CREATE POLICY "Users can insert own trade history" ON trade_history
    FOR INSERT
    WITH CHECK (auth.uid() = user_id);

DROP POLICY IF EXISTS "Users can update own trade history" ON trade_history;
CREATE POLICY "Users can update own trade history" ON trade_history
    FOR UPDATE
    USING (auth.uid() = user_id)
    WITH CHECK (auth.uid() = user_id);
