-- Create a function to cancel pending email changes
-- This function runs with SECURITY DEFINER privileges to access auth.users table
CREATE OR REPLACE FUNCTION public.cancel_user_email_change(_user_id UUID)
RETURNS BOOLEAN
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = auth, public
AS $$
BEGIN
  -- Clear all email change related fields in auth.users
  UPDATE auth.users
  SET 
    email_change = NULL,
    email_change_sent_at = NULL,
    email_change_confirm_status = 0,
    email_change_token_current = NULL,
    email_change_token_new = NULL
  WHERE id = _user_id;
  
  RETURN FOUND;
END;
$$;