-- rTasks module schema
CREATE SCHEMA IF NOT EXISTS rtasks;

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

CREATE TABLE IF NOT EXISTS rtasks.spaces (
	id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
	name TEXT NOT NULL,
	slug TEXT UNIQUE NOT NULL,
	description TEXT,
	icon TEXT,
	owner_did TEXT,
	statuses TEXT[] DEFAULT ARRAY['TODO','IN_PROGRESS','REVIEW','DONE'],
	labels TEXT[] DEFAULT ARRAY['bug','feature','docs','chore'],
	created_at TIMESTAMPTZ DEFAULT NOW(),
	updated_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS rtasks.space_members (
	id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
	space_id UUID NOT NULL REFERENCES rtasks.spaces(id) ON DELETE CASCADE,
	user_id UUID NOT NULL REFERENCES rtasks.users(id) ON DELETE CASCADE,
	role TEXT NOT NULL DEFAULT 'MEMBER' CHECK (role IN ('ADMIN','MODERATOR','MEMBER','VIEWER')),
	joined_at TIMESTAMPTZ DEFAULT NOW(),
	UNIQUE(space_id, user_id)
);

CREATE TABLE IF NOT EXISTS rtasks.tasks (
	id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
	space_id UUID NOT NULL REFERENCES rtasks.spaces(id) ON DELETE CASCADE,
	title TEXT NOT NULL,
	description TEXT,
	status TEXT NOT NULL DEFAULT 'TODO',
	priority TEXT DEFAULT 'MEDIUM' CHECK (priority IN ('LOW','MEDIUM','HIGH','URGENT')),
	labels TEXT[] DEFAULT '{}',
	assignee_id UUID REFERENCES rtasks.users(id),
	created_by UUID REFERENCES rtasks.users(id),
	sort_order INT DEFAULT 0,
	created_at TIMESTAMPTZ DEFAULT NOW(),
	updated_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS rtasks.activity_log (
	id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
	space_id UUID REFERENCES rtasks.spaces(id) ON DELETE CASCADE,
	user_id UUID REFERENCES rtasks.users(id),
	action TEXT NOT NULL,
	metadata JSONB DEFAULT '{}',
	created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_rtasks_tasks_space ON rtasks.tasks(space_id);
CREATE INDEX IF NOT EXISTS idx_rtasks_tasks_status ON rtasks.tasks(space_id, status);
CREATE INDEX IF NOT EXISTS idx_rtasks_activity_space ON rtasks.activity_log(space_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_rtasks_members_user ON rtasks.space_members(user_id);
