-- Add short_user_id column to profiles table
ALTER TABLE profiles ADD COLUMN short_user_id TEXT;

-- Update existing records with the first 6 characters of their id
UPDATE profiles SET short_user_id = LEFT(id::TEXT, 6);

-- Make the column NOT NULL after populating existing records
ALTER TABLE profiles ALTER COLUMN short_user_id SET NOT NULL;

-- Create an index on short_user_id for better query performance
CREATE INDEX idx_profiles_short_user_id ON profiles(short_user_id);

-- Add a trigger to automatically populate short_user_id for new records
CREATE OR REPLACE FUNCTION set_short_user_id()
RETURNS TRIGGER AS $$
BEGIN
    NEW.short_user_id = LEFT(NEW.id::TEXT, 6);
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trigger_set_short_user_id
    BEFORE INSERT ON profiles
    FOR EACH ROW
    EXECUTE FUNCTION set_short_user_id();
