-- Add invite_code to lists table for sharing
ALTER TABLE lists ADD COLUMN IF NOT EXISTS invite_code TEXT UNIQUE;

-- Generate random 8-character invite code for lists that don't have one
UPDATE lists
SET invite_code = UPPER(SUBSTRING(MD5(RANDOM()::TEXT) FROM 1 FOR 8))
WHERE invite_code IS NULL;

-- Automatically insert owner into list_members on list creation if missing
INSERT INTO list_members (list_id, user_id, role)
SELECT id, owner_id, 'owner'
FROM lists
ON CONFLICT (list_id, user_id) DO NOTHING;
