-- Update existing user_preferences records to include unit preferences if they don't have them
UPDATE public.user_preferences 
SET unit_preferences = '{"measurement_system": "metric", "temperature": "celsius", "auto_detect": true}'::jsonb
WHERE unit_preferences IS NULL OR unit_preferences = '{}'::jsonb;

-- Update the initialize_user_preferences function to include unit preferences
CREATE OR REPLACE FUNCTION public.initialize_user_preferences()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = 'public'
AS $function$
BEGIN
  INSERT INTO public.user_preferences (
    user_id,
    unit_preferences
  )
  VALUES (
    NEW.user_id,
    '{"measurement_system": "metric", "temperature": "celsius", "auto_detect": true}'::jsonb
  )
  ON CONFLICT (user_id) DO UPDATE SET
    unit_preferences = COALESCE(public.user_preferences.unit_preferences, '{"measurement_system": "metric", "temperature": "celsius", "auto_detect": true}'::jsonb);
  RETURN NEW;
END;
$function$;