-- ============================================================================
-- OrbiQuant IA - Trading Platform
-- Schema: auth
-- File: functions/01-update_updated_at.sql
-- Description: Trigger function to automatically update updated_at timestamp
-- ============================================================================

CREATE OR REPLACE FUNCTION auth.update_updated_at()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = NOW();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

COMMENT ON FUNCTION auth.update_updated_at() IS 'Trigger function to automatically update updated_at column on row modification';

-- Apply trigger to all tables with updated_at column

-- Users table
CREATE TRIGGER trigger_update_users_updated_at
  BEFORE UPDATE ON auth.users
  FOR EACH ROW
  EXECUTE FUNCTION auth.update_updated_at();

-- User profiles table
CREATE TRIGGER trigger_update_user_profiles_updated_at
  BEFORE UPDATE ON auth.user_profiles
  FOR EACH ROW
  EXECUTE FUNCTION auth.update_updated_at();

-- OAuth accounts table
CREATE TRIGGER trigger_update_oauth_accounts_updated_at
  BEFORE UPDATE ON auth.oauth_accounts
  FOR EACH ROW
  EXECUTE FUNCTION auth.update_updated_at();

-- Sessions table
CREATE TRIGGER trigger_update_sessions_updated_at
  BEFORE UPDATE ON auth.sessions
  FOR EACH ROW
  EXECUTE FUNCTION auth.update_updated_at();

-- Rate limiting config table
CREATE TRIGGER trigger_update_rate_limiting_config_updated_at
  BEFORE UPDATE ON auth.rate_limiting_config
  FOR EACH ROW
  EXECUTE FUNCTION auth.update_updated_at();
