DROP SCHEMA IF EXISTS haystack CASCADE;

CREATE SCHEMA haystack;

/* -----| Schema tables |----- */

CREATE TABLE haystack.users (
	id uuid PRIMARY KEY DEFAULT gen_random_uuid()
);

CREATE TABLE haystack.user_images (
	id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    image_name TEXT NOT NULL,
	image BYTEA NOT NULL,
	user_id uuid NOT NULL REFERENCES haystack.users (id)
);

CREATE TABLE haystack.user_tags (
	id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
	tag TEXT NOT NULL,
	user_id uuid NOT NULL REFERENCES haystack.users (id)
);

CREATE TABLE haystack.image_tags (
	tag_id UUID NOT NULL REFERENCES haystack.user_tags (id),
	image_id UUID NOT NULL REFERENCES haystack.user_images (id)
);

CREATE TABLE haystack.image_text (
	id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
	image_text TEXT NOT NULL,
	image_id UUID NOT NULL REFERENCES haystack.user_images (id)
);

CREATE TABLE haystack.image_links (
	id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
	link TEXT NOT NULL,
	image_id UUID NOT NULL REFERENCES haystack.user_images (id)
);

/* -----| Stored Procedures |----- */

CREATE OR REPLACE FUNCTION notify_new_image()
RETURNS TRIGGER AS $$
BEGIN
	PERFORM pg_notify('new_image', NEW.id::texT);
	RETURN NEW;
END
$$ LANGUAGE plpgsql;

/* -----| Triggers |----- */

CREATE OR REPLACE TRIGGER on_new_image AFTER INSERT
ON haystack.user_images
FOR EACH ROW
EXECUTE PROCEDURE notify_new_image()
