-- Fix the email_change column NULL handling issue in auth.users
-- This addresses the "Scan error on column index 8, name email_change: converting NULL to string is unsupported" error

-- First, create a function to safely update any existing NULL email_change values to empty strings
CREATE OR REPLACE FUNCTION public.fix_auth_email_change_nulls()
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'auth', 'public'
AS $$
BEGIN
  -- Update any NULL email_change values to empty strings
  UPDATE auth.users
  SET email_change = ''
  WHERE email_change IS NULL;
END;
$$;

-- Execute the fix for existing data
SELECT public.fix_auth_email_change_nulls();

-- Drop the temporary function
DROP FUNCTION public.fix_auth_email_change_nulls();

-- Update the cancel_user_email_change function to use empty strings instead of NULL
CREATE OR REPLACE FUNCTION public.cancel_user_email_change(_user_id uuid)
RETURNS boolean
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'auth', 'public'
AS $$
BEGIN
  -- Clear all email change related fields in auth.users
  -- Using empty strings instead of NULL to avoid Supabase Auth scanner issues
  UPDATE auth.users
  SET 
    email_change = '',
    email_change_sent_at = NULL,
    email_change_confirm_status = 0,
    email_change_token_current = '',
    email_change_token_new = ''
  WHERE id = _user_id;
  
  RETURN FOUND;
END;
$$;