CREATE TABLE pads (
 id BIGSERIAL PRIMARY KEY, slug TEXT NOT NULL UNIQUE, title TEXT NOT NULL, content TEXT NOT NULL DEFAULT '', password_hash TEXT,
 created_at TEXT NOT NULL DEFAULT (CURRENT_TIMESTAMP::text), updated_at TEXT NOT NULL DEFAULT (CURRENT_TIMESTAMP::text), owner_map TEXT NOT NULL DEFAULT '[]', file_token TEXT UNIQUE
);
CREATE TABLE revisions (
 id BIGSERIAL PRIMARY KEY, pad_id BIGINT NOT NULL REFERENCES pads(id) ON DELETE CASCADE, content TEXT NOT NULL,
 created_at TEXT NOT NULL DEFAULT (CURRENT_TIMESTAMP::text), author TEXT, owner_map TEXT NOT NULL DEFAULT '[]'
);
CREATE INDEX idx_revisions_pad_id ON revisions(pad_id, id DESC);
CREATE TABLE workspaces (
 id BIGSERIAL PRIMARY KEY, slug TEXT NOT NULL UNIQUE, title TEXT NOT NULL, password_hash TEXT,
 created_at TEXT NOT NULL DEFAULT (CURRENT_TIMESTAMP::text), updated_at TEXT NOT NULL DEFAULT (CURRENT_TIMESTAMP::text)
);
CREATE TABLE notes (
 id BIGSERIAL PRIMARY KEY, workspace_id BIGINT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE, slug TEXT NOT NULL, title TEXT NOT NULL,
 content TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL DEFAULT (CURRENT_TIMESTAMP::text), updated_at TEXT NOT NULL DEFAULT (CURRENT_TIMESTAMP::text),
 owner_map TEXT NOT NULL DEFAULT '[]', file_token TEXT UNIQUE, UNIQUE(workspace_id, slug)
);
CREATE INDEX idx_notes_workspace ON notes(workspace_id, updated_at DESC);
CREATE TABLE note_revisions (
 id BIGSERIAL PRIMARY KEY, note_id BIGINT NOT NULL REFERENCES notes(id) ON DELETE CASCADE, content TEXT NOT NULL,
 created_at TEXT NOT NULL DEFAULT (CURRENT_TIMESTAMP::text), author TEXT, owner_map TEXT NOT NULL DEFAULT '[]'
);
CREATE INDEX idx_note_revisions_note ON note_revisions(note_id, id DESC);
CREATE TABLE published_pages (
 id BIGSERIAL PRIMARY KEY, token TEXT NOT NULL UNIQUE, pad_id BIGINT UNIQUE REFERENCES pads(id) ON DELETE CASCADE,
 note_id BIGINT UNIQUE REFERENCES notes(id) ON DELETE CASCADE, created_at TEXT NOT NULL DEFAULT (CURRENT_TIMESTAMP::text),
 CHECK ((pad_id IS NOT NULL AND note_id IS NULL) OR (pad_id IS NULL AND note_id IS NOT NULL))
);
