{"-- Fix Function Search Path Security Issue
-- Update all existing functions to have proper search_path

-- Fix update_updated_at_column function
CREATE OR REPLACE FUNCTION public.update_modified_column()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO 'public'
AS $function$
BEGIN
  NEW.updated_at = now();
  RETURN NEW;
END;
$function$","-- Fix handle_updated_at function
CREATE OR REPLACE FUNCTION public.update_modified_column()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO 'public'
AS $function$
BEGIN
  NEW.updated_at = now();
  RETURN NEW;
END;
$function$","-- Fix update_subscriber_activity function
CREATE OR REPLACE FUNCTION public.update_subscriber_activity()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO 'public'
AS $function$
BEGIN
    UPDATE public.subscribers 
    SET last_activity = now() 
    WHERE user_id = NEW.user_id OR user_id = OLD.user_id;
    RETURN COALESCE(NEW, OLD);
END;
$function$","-- Fix is_super_admin function
CREATE OR REPLACE FUNCTION public.is_super_admin(user_email text)
 RETURNS boolean
 LANGUAGE sql
 SECURITY DEFINER
 SET search_path TO 'public'
AS $function$
  SELECT user_email = 'ashraffarid@gmail.com'
$function$","-- Fix is_current_user_super_admin function
CREATE OR REPLACE FUNCTION public.is_current_user_super_admin()
 RETURNS boolean
 LANGUAGE sql
 SECURITY DEFINER
 SET search_path TO 'public'
AS $function$
  SELECT public.is_super_admin((SELECT email FROM auth.users WHERE id = auth.uid()))
$function$","-- Fix set_updated_at function
CREATE OR REPLACE FUNCTION public.update_modified_column()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO 'public'
AS $function$
BEGIN
  NEW.updated_at = now();
  RETURN NEW;
END; 
$function$","-- Fix touch_chat_thread function
CREATE OR REPLACE FUNCTION public.touch_chat_thread()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO 'public'
AS $function$
BEGIN
  UPDATE public.chat_threads SET updated_at = now() WHERE id = NEW.thread_id;
  RETURN NEW;
END;
$function$","-- Fix user_is_thread_participant function
CREATE OR REPLACE FUNCTION public.user_is_thread_participant(thread_id uuid)
 RETURNS boolean
 LANGUAGE sql
 SECURITY DEFINER
 SET search_path TO 'public'
AS $function$
  SELECT EXISTS (
    SELECT 1 FROM public.chat_thread_participants p
    WHERE p.thread_id = user_is_thread_participant.thread_id
      AND p.user_id = auth.uid()
  );
$function$","-- Fix other functions with search_path
CREATE OR REPLACE FUNCTION public.update_modified_column()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO 'public'
AS $function$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$function$"}