-- ============================================================================
-- Schema: trading
-- Table: price_alerts
-- Description: Alertas de precio configuradas por usuarios
-- Gap: GAP-DDL-003 (RESOLVED - ST-1.3)
-- Created: 2026-02-03
-- Migration: migrations/2026-02-03_add_price_alerts_symbol_fk.sql
-- ============================================================================

CREATE TABLE trading.price_alerts (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

  -- Relaciones
  user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
  symbol_id UUID NOT NULL REFERENCES trading.symbols(id) ON DELETE CASCADE,

  -- Configuracion de alerta
  condition VARCHAR(10) NOT NULL CHECK (condition IN ('above', 'below', 'crosses')),
  target_price DECIMAL(20,8) NOT NULL CHECK (target_price > 0),

  -- Precio de referencia al crear
  reference_price DECIMAL(20,8),

  -- Estado
  is_active BOOLEAN DEFAULT true,
  is_recurring BOOLEAN DEFAULT false,

  -- Notificacion
  notification_type VARCHAR(20) DEFAULT 'push' CHECK (notification_type IN ('push', 'email', 'both')),
  notification_sent BOOLEAN DEFAULT false,

  -- Ejecucion
  triggered_at TIMESTAMPTZ,
  triggered_price DECIMAL(20,8),
  trigger_count INTEGER DEFAULT 0,

  -- Expiracion opcional
  expires_at TIMESTAMPTZ,

  -- Metadata
  notes VARCHAR(255),

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

-- Indices
CREATE INDEX idx_price_alerts_user ON trading.price_alerts(user_id);
CREATE INDEX idx_price_alerts_symbol ON trading.price_alerts(symbol_id);
CREATE INDEX idx_price_alerts_active ON trading.price_alerts(is_active, symbol_id)
  WHERE is_active = true;
CREATE INDEX idx_price_alerts_expiry ON trading.price_alerts(expires_at)
  WHERE expires_at IS NOT NULL AND is_active = true;

-- Comentarios
COMMENT ON TABLE trading.price_alerts IS 'Alertas de precio configuradas por usuarios';
COMMENT ON COLUMN trading.price_alerts.condition IS 'Condicion: above (>=), below (<=), crosses';
COMMENT ON COLUMN trading.price_alerts.target_price IS 'Precio objetivo para disparar alerta';
COMMENT ON COLUMN trading.price_alerts.is_recurring IS 'Si es true, se reactiva despues de disparar';
COMMENT ON COLUMN trading.price_alerts.notification_type IS 'Tipo de notificacion: push, email, both';
COMMENT ON COLUMN trading.price_alerts.triggered_at IS 'Timestamp de ultima vez que se disparo';
