CREATE TABLE IF NOT EXISTS "user" (
    id UUID NOT NULL,
    pseudo VARCHAR NOT NULL,
    email VARCHAR NOT NULL,
    password VARCHAR NOT NULL,
    photo_id UUID,
    CONSTRAINT user_pk PRIMARY KEY (id)
);

CREATE TABLE IF NOT EXISTS user_role (
    user_id UUID NOT NULL,
    role SMALLINT,
    CONSTRAINT user_role_pk PRIMARY KEY (user_id, role),
    CONSTRAINT user_role_fk_user_id FOREIGN KEY (user_id) REFERENCES "user" (id)
);
CREATE INDEX user_role_fk_user_id_idx ON user_role (user_id);

CREATE TABLE IF NOT EXISTS refresh_token (
    user_id UUID NOT NULL,
    value UUID NOT NULL,
    expiration_date TIMESTAMP NOT NULL,
    CONSTRAINT refresh_token_pk PRIMARY KEY (user_id),
    CONSTRAINT refresh_token_fk_user_id FOREIGN KEY (user_id) REFERENCES "user" (id)
);
CREATE INDEX refresh_token_fk_user_id_idx ON user_role (user_id);

CREATE TABLE IF NOT EXISTS category (
    id UUID NOT NULL,
    name VARCHAR NOT NULL,
    parent_category_id UUID,
    CONSTRAINT category_pk PRIMARY KEY (id),
    CONSTRAINT category_parent_category_id_fk FOREIGN KEY (parent_category_id) REFERENCES category (id)
);
CREATE INDEX category_parent_category_id_idx ON category (parent_category_id);

CREATE TABLE IF NOT EXISTS picture (
    id UUID NOT NULL,
    publisher_id UUID NOT NULL,
    CONSTRAINT picture_pk PRIMARY KEY (id),
    CONSTRAINT picture_publisher_id_fk FOREIGN KEY (publisher_id) REFERENCES "user" (id)
);
CREATE INDEX picture_publisher_id_idx ON picture (publisher_id);

ALTER TABLE "user" ADD CONSTRAINT user_photo_id_fk FOREIGN KEY (photo_id) REFERENCES picture (id);
CREATE INDEX user_photo_id_idx ON "user" (photo_id);

CREATE TABLE IF NOT EXISTS publication (
    id UUID NOT NULL,
    key VARCHAR(14) NOT NULL,
    title VARCHAR NOT NULL,
    text VARCHAR NOT NULL,
    parsed_text VARCHAR,
    description VARCHAR NOT NULL,
    creation_date TIMESTAMP NOT NULL,
    illustration_id UUID NOT NULL,
    author_id UUID NOT NULL,
    category_id UUID NOT NULL,
    CONSTRAINT publication_pk PRIMARY KEY (id),
    CONSTRAINT publication_picture_id_fk FOREIGN KEY (illustration_id) REFERENCES picture (id),
    CONSTRAINT publication_author_id_fk FOREIGN KEY (author_id) REFERENCES "user" (id),
    CONSTRAINT publication_category_id_fk FOREIGN KEY (category_id) REFERENCES category (id)
);
CREATE INDEX publication_picture_id_idx ON publication (illustration_id);
CREATE INDEX publication_author_id_idx ON publication (author_id);
CREATE INDEX publication_category_id_idx ON publication (category_id);

