CREATE TABLE resource_editor_settings (
  resource_kind VARCHAR(32) NOT NULL,
  resource_slug VARCHAR(512) NOT NULL,
  authorship_mode VARCHAR(16) NOT NULL DEFAULT 'simple',
  colors_enabled BOOLEAN NOT NULL DEFAULT TRUE,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (resource_kind, resource_slug)
);

INSERT INTO resource_editor_settings (
  resource_kind, resource_slug, authorship_mode, colors_enabled, updated_at
)
SELECT 'pad', p.slug, preferences.authorship_mode, preferences.colors_enabled,
       CURRENT_TIMESTAMP
FROM user_editor_preferences preferences
JOIN pads p ON p.id = preferences.pad_id
JOIN user_pads ownership
  ON ownership.pad_id = p.id
 AND ownership.user_id = preferences.user_id
WHERE preferences.pad_id IS NOT NULL
ON DUPLICATE KEY UPDATE resource_slug = VALUES(resource_slug);

INSERT INTO resource_editor_settings (
  resource_kind, resource_slug, authorship_mode, colors_enabled, updated_at
)
SELECT 'note', CONCAT(workspace.slug, '/', note.slug),
       preferences.authorship_mode, preferences.colors_enabled,
       CURRENT_TIMESTAMP
FROM user_editor_preferences preferences
JOIN notes note ON note.id = preferences.note_id
JOIN workspaces workspace ON workspace.id = note.workspace_id
JOIN user_workspaces ownership
  ON ownership.workspace_id = workspace.id
 AND ownership.user_id = preferences.user_id
WHERE preferences.note_id IS NOT NULL
ON DUPLICATE KEY UPDATE resource_slug = VALUES(resource_slug);

ALTER TABLE user_editor_preferences
  DROP COLUMN authorship_mode,
  DROP COLUMN colors_enabled;
