CREATE EXTENSION pg_trgm;

CREATE TABLE public.crypto_key (
	id serial4 NOT NULL,
	user_id int4 NOT NULL,
	description varchar(255) DEFAULT ''::character varying NOT NULL,
	"key" bpchar(144) NOT NULL,
	CONSTRAINT crypto_key_pk PRIMARY KEY (id),
	CONSTRAINT crypto_user_description_un UNIQUE (user_id, description),
	CONSTRAINT crypto_key_user_fk FOREIGN KEY (user_id) REFERENCES public."user"(id) ON DELETE RESTRICT ON UPDATE RESTRICT
);

CREATE TABLE public.node (
	id serial4 NOT NULL,
	user_id int4 NOT NULL,
	parent_id int4 NULL,
	"name" varchar(256) DEFAULT ''::character varying NOT NULL,
	"content" text DEFAULT ''::text NOT NULL,
	updated timestamptz DEFAULT now() NOT NULL,
	crypto_key_id int4 NULL,
	content_encrypted text DEFAULT ''::text NOT NULL,
	markdown bool DEFAULT false NOT NULL,
	CONSTRAINT name_length CHECK ((length(TRIM(BOTH FROM name)) > 0)),
	CONSTRAINT node_pk PRIMARY KEY (id),
	CONSTRAINT crypto_key_fk FOREIGN KEY (crypto_key_id) REFERENCES public.crypto_key(id) ON DELETE RESTRICT ON UPDATE RESTRICT,
	CONSTRAINT node_fk FOREIGN KEY (parent_id) REFERENCES public.node(id) ON DELETE RESTRICT ON UPDATE RESTRICT,
	CONSTRAINT node_user_fk FOREIGN KEY (user_id) REFERENCES public."user"(id) ON DELETE RESTRICT ON UPDATE RESTRICT
);
CREATE INDEX node_search_index ON public.node USING gin (name gin_trgm_ops, content gin_trgm_ops);


CREATE OR REPLACE FUNCTION node_update_timestamp()
RETURNS TRIGGER
LANGUAGE PLPGSQL
AS $$
BEGIN
	IF NEW.updated = OLD.updated THEN
		UPDATE node SET updated = NOW() WHERE id=NEW.id;
	END IF;
	RETURN NEW;
END;
$$;

CREATE OR REPLACE TRIGGER node_update AFTER UPDATE ON node
FOR EACH ROW
EXECUTE PROCEDURE node_update_timestamp()
