DROP SCHEMA IF EXISTS haystack CASCADE;

CREATE SCHEMA haystack;

/* -----| Enums |----- */

CREATE TYPE haystack.progress AS ENUM('not-started','in-progress', 'complete');

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

CREATE TABLE haystack.users (
	id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    email TEXT NOT NULL,

    created_at TIMESTAMP WITH TIME ZONE DEFAULT now()
);

CREATE TABLE haystack.image (
	id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES haystack.users (id),

    image_name TEXT NOT NULL,
    description TEXT NOT NULL,

    status haystack.progress NOT NULL DEFAULT 'not-started',

	image BYTEA NOT NULL,

    created_at TIMESTAMP WITH TIME ZONE DEFAULT now()
);

CREATE TABLE haystack.stacks (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES haystack.users (id),

    status haystack.progress NOT NULL DEFAULT 'not-started',

    name TEXT NOT NULL,
    description TEXT NOT NULL,

    created_at TIMESTAMP WITH TIME ZONE DEFAULT now()
);

CREATE TABLE haystack.image_stacks (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    image_id UUID NOT NULL REFERENCES haystack.image (id) ON DELETE CASCADE,
    stack_id UUID NOT NULL REFERENCES haystack.stacks (id) ON DELETE CASCADE
);

CREATE TABLE haystack.schema_items (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    item TEXT NOT NULL,
    value TEXT NOT NULL,
    description TEXT NOT NULL,

    stack_id UUID NOT NULL REFERENCES haystack.stacks (id) ON DELETE CASCADE
);

CREATE TABLE haystack.image_schema_items (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    value TEXT,

    schema_item_id UUID NOT NULL REFERENCES haystack.schema_items (id) ON DELETE CASCADE,
    image_id UUID NOT NULL REFERENCES haystack.image_stacks (id) ON DELETE CASCADE
);
