-- rWork module schema
CREATE SCHEMA IF NOT EXISTS rwork;

CREATE TABLE IF NOT EXISTS rwork.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 rwork.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 rwork.space_members (
	id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
	space_id UUID NOT NULL REFERENCES rwork.spaces(id) ON DELETE CASCADE,
	user_id UUID NOT NULL REFERENCES rwork.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 rwork.tasks (
	id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
	space_id UUID NOT NULL REFERENCES rwork.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 rwork.users(id),
	created_by UUID REFERENCES rwork.users(id),
	sort_order INT DEFAULT 0,
	created_at TIMESTAMPTZ DEFAULT NOW(),
	updated_at TIMESTAMPTZ DEFAULT NOW()
);

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

CREATE INDEX IF NOT EXISTS idx_rwork_tasks_space ON rwork.tasks(space_id);
CREATE INDEX IF NOT EXISTS idx_rwork_tasks_status ON rwork.tasks(space_id, status);
CREATE INDEX IF NOT EXISTS idx_rwork_activity_space ON rwork.activity_log(space_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_rwork_members_user ON rwork.space_members(user_id);
