-- Create RPC function to get users with emails for admin/superuser
CREATE OR REPLACE FUNCTION public.get_users_with_emails()
RETURNS TABLE (
  id uuid,
  user_id uuid,
  username text,
  email text,
  display_name text,
  avatar_url text,
  banned boolean,
  created_at timestamptz
)
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public', 'auth'
AS $$
BEGIN
  -- Check if caller is superuser or admin
  IF NOT EXISTS (
    SELECT 1 FROM public.user_roles
    WHERE user_roles.user_id = auth.uid()
    AND role IN ('superuser', 'admin')
  ) THEN
    RAISE EXCEPTION 'Access denied: requires admin or superuser role'
      USING ERRCODE = '42501';
  END IF;

  -- Return profiles with emails from auth.users
  RETURN QUERY
  SELECT 
    p.id,
    p.user_id,
    p.username,
    COALESCE(au.email, 'unknown@email.com') as email,
    p.display_name,
    p.avatar_url,
    p.banned,
    p.created_at
  FROM public.profiles p
  LEFT JOIN auth.users au ON au.id = p.user_id
  ORDER BY p.created_at DESC;
END;
$$;