-- TODO: Add the following fields where its defined in the model
-- created_at
-- updated_at
-- deleted_at


-- +migrate Up
CREATE TYPE Rating AS ENUM (
    'safe',
    'questionable',
    'explicit'
    );

CREATE TYPE TagType AS ENUM (
    'general',
    'species',
    'character',
    'artist',
    'lore',
    'meta',
    'invalid'
    );

CREATE TABLE "Post"
(
    id         VARCHAR(25) UNIQUE PRIMARY KEY,
    rating     Rating,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE "Source"
(
    id   VARCHAR(25) UNIQUE PRIMARY KEY,
    display_name TEXT,
    icon TEXT,
    domain       TEXT NOT NULL UNIQUE
);

CREATE TABLE "Tag"
(
    name TEXT PRIMARY KEY,
    type TagType
);

CREATE TABLE "User"
(
    id         TEXT UNIQUE PRIMARY KEY,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE "PostReference"
(
    post_id        TEXT REFERENCES "Post" (id),
    source_id      TEXT REFERENCES "Source" (id),
    url            TEXT NOT NULL UNIQUE,
    source_post_id TEXT,
    PRIMARY KEY (post_id, source_id)
);

CREATE TABLE "TagAlias"
(
    name   TEXT PRIMARY KEY,
    tag_id TEXT REFERENCES "Tag" (name)
);

CREATE TABLE "TagGroup"
(
    name   TEXT PRIMARY KEY,
    tag_id TEXT REFERENCES "Tag" (name)
);

CREATE TABLE "UserFavorites"
(
    user_id    TEXT REFERENCES "User" (id),
    post_id    TEXT REFERENCES "Post" (id),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (user_id, post_id)
);

CREATE TABLE "UserSource"
(
    user_id          TEXT REFERENCES "User" (id),
    source_id        TEXT REFERENCES "Source" (id),
    account_username TEXT,
    account_id       TEXT,
    PRIMARY KEY (user_id, source_id)
);

-- +migrate Down
DROP TYPE Rating;
DROP TYPE TagType;
DROP TYPE Post;
DROP TYPE Source;
DROP TYPE Tag;
DROP TYPE User;
DROP TYPE PostReference;
DROP TYPE TagAlias;
DROP TYPE TagGroup;
DROP TYPE UserFavorites;
DROP TYPE UserSource;