CREATE SCHEMA IF NOT EXISTS ugc;

CREATE TYPE ugc.status_type AS ENUM (
    'active',
    'done',
    'expired',
    'skipped'
);

CREATE TABLE ugc.contribution (
    uid bigint NOT NULL,
    contribution_id text NOT NULL,
    metadata_id bigint NOT NULL,
    created_at timestamp with time zone NOT NULL DEFAULT NOW(),

    CONSTRAINT contribution_pkey PRIMARY KEY (uid, contribution_id)
);

CREATE INDEX ON ugc.contribution USING btree (uid, created_at);


CREATE TABLE ugc.contribution_data (
    uid bigint NOT NULL,
    contribution_id text NOT NULL,
    locale text NOT NULL,
    data text NOT NULL,

    CONSTRAINT contribution_data_pkey PRIMARY KEY (uid, contribution_id, locale),

    CONSTRAINT contribution_data_uid_contribution_id_fkey
        FOREIGN KEY (uid, contribution_id)
        REFERENCES ugc.contribution (uid, contribution_id)
        ON UPDATE NO ACTION ON DELETE CASCADE
);


CREATE TABLE ugc.assignment (
    uid bigint NOT NULL,
    task_id text NOT NULL,
    metadata_id bigint NOT NULL,
    created_at timestamp with time zone NOT NULL DEFAULT NOW(),
    updated_at timestamp with time zone NOT NULL DEFAULT NOW(),
    expired_at timestamp with time zone,
    status ugc.status_type NOT NULL,

    CONSTRAINT assignment_pkey PRIMARY KEY (uid, task_id)
);

CREATE TABLE ugc.assignment_data (
    uid bigint NOT NULL,
    task_id text NOT NULL,
    locale text NOT NULL,
    data text NOT NULL,

    CONSTRAINT assignment_data_pkey PRIMARY KEY (uid, task_id, locale),

    CONSTRAINT assignment_data_uid_task_id_fkey FOREIGN KEY (uid, task_id)
        REFERENCES ugc.assignment (uid, task_id)
        ON UPDATE NO ACTION ON DELETE CASCADE
);


CREATE TABLE ugc.links (
    uid bigint NOT NULL,
    contribution_id text NOT NULL,
    task_id text NOT NULL,

    CONSTRAINT links_pkey PRIMARY KEY (uid, contribution_id, task_id),

    CONSTRAINT links_uid_contribution_id_fkey
        FOREIGN KEY (uid, contribution_id)
        REFERENCES ugc.contribution (uid, contribution_id)
        ON UPDATE NO ACTION ON DELETE CASCADE,

    CONSTRAINT links_uid_task_id_fkey FOREIGN KEY (uid, task_id)
        REFERENCES ugc.assignment (uid, task_id)
        ON UPDATE NO ACTION ON DELETE CASCADE
);

CREATE INDEX ON ugc.links USING btree (uid, task_id);
