-- rNotes module schema
CREATE SCHEMA IF NOT EXISTS rnotes;

-- Users
CREATE TABLE IF NOT EXISTS rnotes.users (
	id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
	did TEXT UNIQUE NOT NULL,
	username TEXT,
	created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Notebooks
CREATE TABLE IF NOT EXISTS rnotes.notebooks (
	id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
	title TEXT NOT NULL DEFAULT 'Untitled Notebook',
	slug TEXT,
	description TEXT,
	cover_color TEXT DEFAULT '#3b82f6',
	is_public BOOLEAN DEFAULT FALSE,
	created_at TIMESTAMPTZ DEFAULT NOW(),
	updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Notebook collaborators
CREATE TABLE IF NOT EXISTS rnotes.notebook_collaborators (
	id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
	user_id UUID NOT NULL REFERENCES rnotes.users(id) ON DELETE CASCADE,
	notebook_id UUID NOT NULL REFERENCES rnotes.notebooks(id) ON DELETE CASCADE,
	role TEXT DEFAULT 'EDITOR' CHECK (role IN ('OWNER','EDITOR','VIEWER')),
	joined_at TIMESTAMPTZ DEFAULT NOW(),
	UNIQUE(user_id, notebook_id)
);

-- Tags
CREATE TABLE IF NOT EXISTS rnotes.tags (
	id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
	name TEXT UNIQUE NOT NULL
);

-- Notes
CREATE TABLE IF NOT EXISTS rnotes.notes (
	id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
	notebook_id UUID REFERENCES rnotes.notebooks(id) ON DELETE CASCADE,
	author_id UUID REFERENCES rnotes.users(id),
	title TEXT NOT NULL DEFAULT 'Untitled',
	content TEXT DEFAULT '',
	content_plain TEXT,
	type TEXT DEFAULT 'NOTE' CHECK (type IN ('NOTE','CLIP','BOOKMARK','CODE','IMAGE','FILE','AUDIO')),
	url TEXT,
	language TEXT,
	file_url TEXT,
	mime_type TEXT,
	file_size INTEGER,
	duration INTEGER,
	is_pinned BOOLEAN DEFAULT FALSE,
	sort_order INTEGER DEFAULT 0,
	created_at TIMESTAMPTZ DEFAULT NOW(),
	updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Note tags (many-to-many)
CREATE TABLE IF NOT EXISTS rnotes.note_tags (
	note_id UUID NOT NULL REFERENCES rnotes.notes(id) ON DELETE CASCADE,
	tag_id UUID NOT NULL REFERENCES rnotes.tags(id) ON DELETE CASCADE,
	PRIMARY KEY (note_id, tag_id)
);

-- Indexes
CREATE INDEX IF NOT EXISTS idx_notes_notebook ON rnotes.notes(notebook_id);
CREATE INDEX IF NOT EXISTS idx_notes_author ON rnotes.notes(author_id);
CREATE INDEX IF NOT EXISTS idx_notes_type ON rnotes.notes(type);
CREATE INDEX IF NOT EXISTS idx_collaborators_notebook ON rnotes.notebook_collaborators(notebook_id);
