-- ============================================================================
-- SCHEMA: users
-- TABLE: user_settings
-- DESCRIPTION: Configuraciones y preferencias de usuario
-- VERSION: 1.0.0
-- CREATED: 2026-01-16
-- SPRINT: Sprint 1 - DDL Implementation Roadmap Q1-2026
-- ============================================================================

-- Tabla de Configuraciones de Usuario
CREATE TABLE IF NOT EXISTS users.user_settings (
    -- Identificadores
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL UNIQUE REFERENCES users.users(id) ON DELETE CASCADE,
    tenant_id UUID NOT NULL REFERENCES tenants.tenants(id) ON DELETE CASCADE,

    -- Configuraciones de UI
    ui_settings JSONB NOT NULL DEFAULT '{
        "theme": "dark",
        "sidebar_collapsed": false,
        "dashboard_layout": "default",
        "charts_theme": "dark",
        "compact_mode": false,
        "animations_enabled": true
    }'::JSONB,

    -- Configuraciones de Trading
    trading_settings JSONB NOT NULL DEFAULT '{
        "default_leverage": 1,
        "risk_per_trade_percent": 2,
        "default_stop_loss_pips": 50,
        "default_take_profit_pips": 100,
        "confirmation_required": true,
        "one_click_trading": false,
        "sound_enabled": true
    }'::JSONB,

    -- Configuraciones de Notificaciones
    notification_settings JSONB NOT NULL DEFAULT '{
        "email": {
            "enabled": true,
            "signals": true,
            "trades": true,
            "account": true,
            "marketing": false,
            "digest": "daily"
        },
        "push": {
            "enabled": true,
            "signals": true,
            "trades": true,
            "price_alerts": true
        },
        "sms": {
            "enabled": false,
            "critical_only": true
        }
    }'::JSONB,

    -- Configuraciones de Privacidad
    privacy_settings JSONB NOT NULL DEFAULT '{
        "profile_visibility": "private",
        "show_in_leaderboard": false,
        "share_performance": false,
        "allow_follow": false
    }'::JSONB,

    -- Configuraciones de Seguridad
    security_settings JSONB NOT NULL DEFAULT '{
        "session_timeout_minutes": 30,
        "remember_devices": true,
        "login_notifications": true,
        "suspicious_activity_alerts": true
    }'::JSONB,

    -- Configuraciones de Datos de Mercado
    market_data_settings JSONB NOT NULL DEFAULT '{
        "default_symbols": ["EURUSD", "GBPUSD", "XAUUSD"],
        "default_timeframe": "H1",
        "price_decimals": 5,
        "volume_display": "lots"
    }'::JSONB,

    -- Preferencias de reportes
    report_settings JSONB NOT NULL DEFAULT '{
        "default_period": "monthly",
        "include_closed_trades": true,
        "currency_display": "USD"
    }'::JSONB,

    -- Metadata
    metadata JSONB DEFAULT '{}'::JSONB,

    -- Timestamps
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

COMMENT ON TABLE users.user_settings IS
'Configuraciones y preferencias personalizables del usuario';

COMMENT ON COLUMN users.user_settings.ui_settings IS
'Configuraciones de interfaz: tema, layouts, preferencias visuales';

COMMENT ON COLUMN users.user_settings.trading_settings IS
'Configuraciones de trading: leverage, risk, confirmaciones';

COMMENT ON COLUMN users.user_settings.notification_settings IS
'Preferencias de notificaciones por canal';

-- Indices
CREATE INDEX IF NOT EXISTS idx_user_settings_user_id
    ON users.user_settings(user_id);

CREATE INDEX IF NOT EXISTS idx_user_settings_tenant_id
    ON users.user_settings(tenant_id);

-- GIN index para busquedas en JSONB
CREATE INDEX IF NOT EXISTS idx_user_settings_ui_gin
    ON users.user_settings USING GIN (ui_settings);

CREATE INDEX IF NOT EXISTS idx_user_settings_notif_gin
    ON users.user_settings USING GIN (notification_settings);

-- Trigger para updated_at
DROP TRIGGER IF EXISTS user_settings_updated_at ON users.user_settings;
CREATE TRIGGER user_settings_updated_at
    BEFORE UPDATE ON users.user_settings
    FOR EACH ROW
    EXECUTE FUNCTION users.update_user_timestamp();

-- RLS Policy para multi-tenancy
ALTER TABLE users.user_settings ENABLE ROW LEVEL SECURITY;

CREATE POLICY user_settings_tenant_isolation ON users.user_settings
    FOR ALL
    USING (tenant_id = current_setting('app.current_tenant_id', true)::UUID);

-- Grants
GRANT SELECT, INSERT, UPDATE ON users.user_settings TO trading_app;
GRANT SELECT ON users.user_settings TO trading_readonly;
