-- BEGIN;

-- -- Add first_name and last_name columns to profiles table
-- ALTER TABLE profiles 
-- ADD COLUMN first_name TEXT,
-- ADD COLUMN last_name TEXT;

-- -- Optionally, populate existing records by splitting the name column
-- -- This assumes names are in "FirstName LastName" format
-- UPDATE profiles 
-- SET 
--     first_name = SPLIT_PART(name, ' ', 1),
--     last_name = CASE 
--         WHEN ARRAY_LENGTH(STRING_TO_ARRAY(name, ' '), 1) > 1 
--         THEN SUBSTRING(name FROM LENGTH(SPLIT_PART(name, ' ', 1)) + 2)
--         ELSE NULL
--     END
-- WHERE name IS NOT NULL;

-- COMMIT;

-- Add comments to describe the columns
COMMENT ON COLUMN profiles.first_name IS 'User''s first name';
COMMENT ON COLUMN profiles.last_name IS 'User''s last name';

CREATE OR REPLACE FUNCTION
  public.handle_new_user()
  RETURNS TRIGGER AS
  $$
  DECLARE 
    name TEXT;
    first_name TEXT;
    last_name TEXT;
  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;

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