ALTER TABLE pads ADD COLUMN owner_map TEXT NOT NULL DEFAULT '[]';
ALTER TABLE pads ADD COLUMN file_token TEXT;
CREATE UNIQUE INDEX IF NOT EXISTS idx_pads_file_token ON pads(file_token);
ALTER TABLE revisions ADD COLUMN author TEXT;
ALTER TABLE revisions ADD COLUMN owner_map TEXT NOT NULL DEFAULT '[]';

CREATE TABLE IF NOT EXISTS workspaces (
 id INTEGER PRIMARY KEY AUTOINCREMENT, slug TEXT NOT NULL UNIQUE, title TEXT NOT NULL, password_hash TEXT,
 created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS notes (
 id INTEGER PRIMARY KEY AUTOINCREMENT, workspace_id INTEGER NOT NULL, slug TEXT NOT NULL, title TEXT NOT NULL, content TEXT NOT NULL DEFAULT '',
 created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, owner_map TEXT NOT NULL DEFAULT '[]', file_token TEXT UNIQUE,
 protected INTEGER NOT NULL DEFAULT 0, FOREIGN KEY (workspace_id) REFERENCES workspaces(id) ON DELETE CASCADE, UNIQUE(workspace_id, slug)
);
CREATE INDEX IF NOT EXISTS idx_notes_workspace ON notes(workspace_id, updated_at DESC);
CREATE TABLE IF NOT EXISTS note_revisions (
 id INTEGER PRIMARY KEY AUTOINCREMENT, note_id INTEGER NOT NULL, content TEXT NOT NULL, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
 author TEXT, owner_map TEXT NOT NULL DEFAULT '[]', FOREIGN KEY (note_id) REFERENCES notes(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_note_revisions_note ON note_revisions(note_id, id DESC);
CREATE TABLE IF NOT EXISTS published_pages (
 id INTEGER PRIMARY KEY AUTOINCREMENT, token TEXT NOT NULL UNIQUE, pad_id INTEGER UNIQUE, note_id INTEGER UNIQUE, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
 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))
);
CREATE TABLE IF NOT EXISTS note_files (
 id INTEGER PRIMARY KEY AUTOINCREMENT, note_id INTEGER NOT NULL, filename TEXT NOT NULL, url TEXT NOT NULL UNIQUE, mime_type TEXT NOT NULL,
 size_bytes INTEGER NOT NULL, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, is_attached INTEGER NOT NULL DEFAULT 1, detached_at TEXT,
 FOREIGN KEY (note_id) REFERENCES notes(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_note_files_note ON note_files(note_id, id DESC);
