CREATE TABLE resource_editor_settings (
  resource_kind TEXT NOT NULL,
  resource_slug TEXT NOT NULL,
  authorship_mode TEXT NOT NULL DEFAULT 'simple',
  colors_enabled BOOLEAN NOT NULL DEFAULT TRUE,
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  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,
       preferences.updated_at::timestamptz
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 CONFLICT (resource_kind, resource_slug) DO NOTHING;

INSERT INTO resource_editor_settings (
  resource_kind, resource_slug, authorship_mode, colors_enabled, updated_at
)
SELECT 'note', workspace.slug || '/' || note.slug,
       preferences.authorship_mode, preferences.colors_enabled,
       preferences.updated_at::timestamptz
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 CONFLICT (resource_kind, resource_slug) DO NOTHING;

ALTER TABLE user_editor_preferences
  DROP COLUMN authorship_mode,
  DROP COLUMN colors_enabled;
