CREATE TABLE resource_editor_settings (
  resource_kind TEXT NOT NULL,
  resource_slug TEXT NOT NULL,
  authorship_mode TEXT NOT NULL DEFAULT 'simple',
  colors_enabled INTEGER NOT NULL DEFAULT 1,
  updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (resource_kind, resource_slug)
);

INSERT OR IGNORE 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
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;

INSERT OR IGNORE 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
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;

ALTER TABLE user_editor_preferences RENAME TO user_editor_preferences_legacy;

CREATE TABLE user_editor_preferences (
  user_id INTEGER NOT NULL,
  pad_id INTEGER,
  note_id INTEGER,
  compact_view INTEGER NOT NULL DEFAULT 1,
  editor_line_numbers INTEGER NOT NULL DEFAULT 1,
  preview_line_numbers INTEGER NOT NULL DEFAULT 0,
  line_links INTEGER NOT NULL DEFAULT 0,
  font_family TEXT NOT NULL DEFAULT 'mono',
  font_size INTEGER NOT NULL DEFAULT 14,
  updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  FOREIGN KEY (pad_id) REFERENCES pads(id) ON DELETE CASCADE,
  FOREIGN KEY (note_id) REFERENCES notes(id) ON DELETE CASCADE,
  CHECK ((pad_id IS NOT NULL AND note_id IS NULL) OR (pad_id IS NULL AND note_id IS NOT NULL)),
  UNIQUE (user_id, pad_id),
  UNIQUE (user_id, note_id)
);

INSERT INTO user_editor_preferences (
  user_id, pad_id, note_id, compact_view, editor_line_numbers,
  preview_line_numbers, line_links, font_family, font_size, updated_at
)
SELECT user_id, pad_id, note_id, compact_view, editor_line_numbers,
       preview_line_numbers, line_links, font_family, font_size, updated_at
FROM user_editor_preferences_legacy;

DROP TABLE user_editor_preferences_legacy;

CREATE INDEX idx_user_editor_preferences_user ON user_editor_preferences(user_id);
CREATE INDEX idx_user_editor_preferences_pad ON user_editor_preferences(pad_id);
CREATE INDEX idx_user_editor_preferences_note ON user_editor_preferences(note_id);
