-- Migration: Add device_type column to device_registrations table
DO $$ 
BEGIN
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns 
                   WHERE table_name = 'device_registrations' AND column_name = 'device_type') THEN
        ALTER TABLE device_registrations ADD COLUMN device_type VARCHAR(50) DEFAULT 'unknown';
        
        -- Update existing records to have a device_type based on operating system
        UPDATE device_registrations 
        SET device_type = CASE 
            WHEN operating_system ILIKE '%windows%' THEN 'desktop'
            WHEN operating_system ILIKE '%mac%' THEN 'desktop'
            WHEN operating_system ILIKE '%linux%' THEN 'desktop'
            WHEN operating_system ILIKE '%android%' THEN 'mobile'
            WHEN operating_system ILIKE '%ios%' THEN 'mobile'
            ELSE 'unknown'
        END
        WHERE device_type IS NULL OR device_type = 'unknown';
    END IF;
END $$;