-- Enhance invalidate_banned_user_sessions trigger to handle both ban and unban events
CREATE OR REPLACE FUNCTION public.invalidate_banned_user_sessions()
RETURNS TRIGGER
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
BEGIN
  -- If user was just banned (banned changed from false to true)
  IF NEW.banned = true AND OLD.banned = false THEN
    PERFORM pg_notify(
      'user_banned',
      json_build_object(
        'user_id', NEW.user_id,
        'username', NEW.username,
        'banned_at', NOW(),
        'action', 'banned'
      )::text
    );
  END IF;
  
  -- If user was just unbanned (banned changed from true to false)
  IF NEW.banned = false AND OLD.banned = true THEN
    PERFORM pg_notify(
      'user_unbanned',
      json_build_object(
        'user_id', NEW.user_id,
        'username', NEW.username,
        'unbanned_at', NOW(),
        'action', 'unbanned'
      )::text
    );
  END IF;
  
  RETURN NEW;
END;
$$;