CREATE TABLE users (
	id BLOB NOT NULL PRIMARY KEY DEFAULT (uuid_blob(uuid())),
	oidc_sub TEXT UNIQUE,
	name TEXT NOT NULL,
	email TEXT NOT NULL UNIQUE,
	admin BOOLEAN NOT NULL DEFAULT FALSE,
	hash TEXT,
	updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
	created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE warrens (
	id BLOB NOT NULL PRIMARY KEY DEFAULT (uuid_blob(uuid())),
	name TEXT NOT NULL,
	path TEXT NOT NULL UNIQUE,
	created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE user_warrens (
	user_id BLOB NOT NULL REFERENCES users(id) ON DELETE CASCADE,
	warren_id BLOB NOT NULL REFERENCES warrens(id) ON DELETE CASCADE,
	can_list_files BOOLEAN NOT NULL,
	can_read_files  BOOLEAN NOT NULL,
	can_modify_files BOOLEAN NOT NULL,
	can_delete_files BOOLEAN NOT NULL,
	can_list_shares BOOLEAN NOT NULL,
	can_create_shares BOOLEAN NOT NULL,
	can_modify_shares BOOLEAN NOT NULL,
	can_delete_shares BOOLEAN NOT NULL,
	PRIMARY KEY(user_id, warren_id)
);

CREATE TABLE shares (
	id BLOB NOT NULL PRIMARY KEY DEFAULT (uuid_blob(uuid())),
	creator_id BLOB NOT NULL REFERENCES users(id) ON DELETE CASCADE,
	warren_id BLOB NOT NULL REFERENCES warrens(id) ON DELETE CASCADE,
	path TEXT NOT NULL,
	password_hash TEXT,
	expires_at DATETIME,
	created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_shares_path ON shares(path);

CREATE TABLE auth_sessions (
	session_id TEXT NOT NULL PRIMARY KEY,
	user_id BLOB NOT NULL REFERENCES users(id) ON DELETE CASCADE,
	expires_at DATETIME NOT NULL,
	created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
