
DROP TABLE IF EXISTS Users CASCADE;
DROP TABLE IF EXISTS Support CASCADE;
DROP TABLE IF EXISTS Quote CASCADE;
DROP TABLE IF EXISTS Commentary CASCADE;
DROP TABLE IF EXISTS Favorite CASCADE;
DROP TABLE IF EXISTS QuizQuestions CASCADE;
DROP TABLE IF EXISTS Quiz CASCADE;
DROP TABLE IF EXISTS Question CASCADE;

CREATE TABLE Users (
    id_user     SERIAL      PRIMARY KEY,
    username    varchar(50) NOT NULL,
    email       varchar(50) NOT NULL,
    phone       varchar(10) NOT NULL,
    pssword     varchar(99) NOT NULL,
    creation    date        NOT NULL,
    CONSTRAINT  unique_col  UNIQUE (username, email, phone)
);


CREATE TABLE Support (
    id_support  SERIAL      PRIMARY KEY,
    title       varchar(99) NOT NULL,
    form        varchar(30) NOT NULL,
    release     numeric     NOT NULL,
    CONSTRAINT  type_form   CHECK (form IN ('movie', 'video-game', 'novel', 'anime', 'tv'))
);

CREATE TABLE Quote (
    id_quote    SERIAL      PRIMARY KEY,
    content     text        NOT NULL UNIQUE,
    img_path    varchar(50) NOT NULL,
    likes       numeric     NOT NULL DEFAULT 0,
    time_code   varchar(10) NOT NULL,
    langue      varchar(50) NOT NULL,
    is_valid    boolean     NOT NULL DEFAULT true,
    reason      text,
    user_q      integer     REFERENCES Users(id_user),
    support     integer     REFERENCES Support(id_support),
    CONSTRAINT  reason_txt  CHECK (is_valid OR reason IS NOT NULL)
);

CREATE TABLE Commentary (
    id_comment  numeric     PRIMARY KEY,
    comment     text        NOT NULL,
    user_c      integer     REFERENCES Users(id_user),
    quote_c     integer     REFERENCES Quote(id_quote)
);

CREATE TABLE Favorite (
    user_f      integer     REFERENCES Users(id_user),
    quote_f     integer     REFERENCES Quote(id_quote),
    CONSTRAINT  pk_favorite PRIMARY KEY (user_f, quote_f)
);

CREATE TABLE Quiz (
    id_quiz     numeric     PRIMARY KEY,
    level       numeric     NOT NULL,
    duration    numeric     NOT NULL
);

CREATE TABLE Question (
    id_question numeric     PRIMARY KEY,
    question    varchar(99) NOT NULL,
    answerA     varchar(99) NOT NULL,
    answerB     varchar(99) NOT NULL,
    answerC     varchar(99) NOT NULL,
    answerD     varchar(99) NOT NULL,
    cAnswer     varchar(99) NOT NULL
);

CREATE TABLE QuizQuestions (
    quiz_qq     numeric     REFERENCES Quiz(id_quiz),
    question_qq numeric     REFERENCES Question(id_question),
    CONSTRAINT  pk_qq       PRIMARY KEY (quiz_qq, question_qq)
);