-- Modify the handle_new_user trigger to set is_temporary based on app_metadata.role
CREATE OR REPLACE FUNCTION
  public.handle_new_user()
  RETURNS TRIGGER AS
  $$
  DECLARE 
    name TEXT;
    first_name TEXT;
    last_name TEXT;
    is_temp BOOLEAN;
  BEGIN   
  -- Extract first_name and last_name from metadata
  first_name = new.raw_user_meta_data ->> 'first_name';
  last_name = new.raw_user_meta_data ->> 'last_name';
  
  -- Determine the full name
  IF new.raw_user_meta_data ->> 'name' IS NOT NULL
  THEN
    name = new.raw_user_meta_data ->> 'name';
    -- If name is provided but not first/last, try to split it
    IF first_name IS NULL AND last_name IS NULL AND name IS NOT NULL THEN
      first_name = SPLIT_PART(name, ' ', 1);
      IF ARRAY_LENGTH(STRING_TO_ARRAY(name, ' '), 1) > 1 THEN
        last_name = SUBSTRING(name FROM LENGTH(SPLIT_PART(name, ' ', 1)) + 2);
      END IF;
    END IF;
  ELSE
    name = CONCAT(first_name, ' ', last_name);
  END IF;

  -- Check if the role is 'invited_user' in app_metadata
  IF COALESCE(new.raw_user_meta_data->>'role', '') = 'invited_user'
  THEN
    is_temp = TRUE;
  ELSE
    is_temp = FALSE;
  END IF;

  INSERT INTO public.profiles (id, name, email, avatar_url, first_name, last_name, is_temporary)
  VALUES (new.id, name, new.email, new.raw_user_meta_data ->> 'avatar_url', first_name, last_name, is_temp);
  
  RETURN new;
END;
  $$ LANGUAGE plpgsql SECURITY DEFINER;

-- Add comment to document the change
COMMENT ON FUNCTION public.handle_new_user() IS 
    'Trigger function that creates a profile when a new user is created. Sets is_temporary=true for users with app_metadata.role=invited_user';

