-- ============================================================
-- Migration 016: Add Strategy Marketplace
-- Purpose: Support publishing of trade profiles to a marketplace as templates.
-- ============================================================

CREATE TABLE IF NOT EXISTS public.strategy_presets (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    description TEXT,
    risk_style_id TEXT DEFAULT 'balanced',
    recommended_assets TEXT[],
    typical_trades_per_day TEXT,
    performance_tag TEXT,
    is_popular BOOLEAN DEFAULT false,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    created_by UUID REFERENCES auth.users(id),
    original_profile_id UUID REFERENCES public.trade_profiles(id),
    strategy_config JSONB,
    role_required TEXT DEFAULT 'free'
);

COMMENT ON TABLE public.strategy_presets IS 'Marketplace templates for trading strategies published by admins';
COMMENT ON COLUMN public.strategy_presets.strategy_config IS 'Full rule and risk configuration snapshot for the template';

-- Enable Row Level Security and Realtime
ALTER TABLE public.strategy_presets ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.strategy_presets REPLICA IDENTITY FULL;

-- Policy: Everyone can read strategy presets
DROP POLICY IF EXISTS "Everyone can read presets" ON public.strategy_presets;
CREATE POLICY "Everyone can read presets" ON public.strategy_presets
    FOR SELECT USING (true);

-- Policy: Only admins can insert/update/delete strategy presets
DROP POLICY IF EXISTS "Admins can manage presets" ON public.strategy_presets;
CREATE POLICY "Admins can manage presets" ON public.strategy_presets
    USING (
        EXISTS (
            SELECT 1 FROM public.users 
            WHERE user_id = auth.uid() AND role = 'admin'
        )
    )
    WITH CHECK (
        EXISTS (
            SELECT 1 FROM public.users 
            WHERE user_id = auth.uid() AND role = 'admin'
        )
    );

-- Create index for faster marketplace loading
CREATE INDEX IF NOT EXISTS idx_strategy_presets_risk_style ON public.strategy_presets(risk_style_id);
CREATE INDEX IF NOT EXISTS idx_strategy_presets_is_popular ON public.strategy_presets(is_popular);
