-- Migration 011: Create user_preferences table for persistent user settings
-- Stores user-specific preferences like rows per page, default filters, etc.

CREATE TABLE IF NOT EXISTS user_preferences (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    preference_key VARCHAR(100) NOT NULL,
    preference_value TEXT,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY unique_user_pref (user_id, preference_key),
    FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE CASCADE
);

-- Default preferences for existing users
INSERT INTO user_preferences (user_id, preference_key, preference_value)
SELECT user_id, 'rows_per_page', '15' FROM users
WHERE user_id NOT IN (SELECT user_id FROM user_preferences WHERE preference_key = 'rows_per_page');

INSERT INTO user_preferences (user_id, preference_key, preference_value)
SELECT user_id, 'default_status_filters', 'Open,Pending,In Progress' FROM users
WHERE user_id NOT IN (SELECT user_id FROM user_preferences WHERE preference_key = 'default_status_filters');

INSERT INTO user_preferences (user_id, preference_key, preference_value)
SELECT user_id, 'table_density', 'normal' FROM users
WHERE user_id NOT IN (SELECT user_id FROM user_preferences WHERE preference_key = 'table_density');

INSERT INTO user_preferences (user_id, preference_key, preference_value)
SELECT user_id, 'notifications_enabled', '1' FROM users
WHERE user_id NOT IN (SELECT user_id FROM user_preferences WHERE preference_key = 'notifications_enabled');

INSERT INTO user_preferences (user_id, preference_key, preference_value)
SELECT user_id, 'sound_effects', '1' FROM users
WHERE user_id NOT IN (SELECT user_id FROM user_preferences WHERE preference_key = 'sound_effects');

INSERT INTO user_preferences (user_id, preference_key, preference_value)
SELECT user_id, 'toast_duration', '3000' FROM users
WHERE user_id NOT IN (SELECT user_id FROM user_preferences WHERE preference_key = 'toast_duration');

-- Verify table created
SELECT 'User Preferences Table Created' as info;
DESCRIBE user_preferences;

-- Show count of preferences
SELECT 'Default Preferences Inserted' as info;
SELECT preference_key, COUNT(*) as user_count
FROM user_preferences
GROUP BY preference_key
ORDER BY preference_key;
