CREATE TABLE users
(
    id          SERIAL PRIMARY KEY,
    mail        VARCHAR(255) NOT NULL,
    name        VARCHAR(150) NOT NULL,
    time_create BIGINT       NOT NULL,
    time_update BIGINT       NOT NULL
);

CREATE TABLE token
(
    id               SERIAL PRIMARY KEY,
    label            VARCHAR(150) NOT NULL,
    time_create      BIGINT       NOT NULL,
    time_update      BIGINT       NOT NULL,
    user_id          INTEGER      NOT NULL REFERENCES users ON DELETE CASCADE,
    token_value      VARCHAR(150) NOT NULL,
    time_used        BIGINT       NOT NULL,
    max_inactivity   INTEGER,
    ip_restriction   VARCHAR(50),
    read_only        BOOLEAN      NOT NULL DEFAULT true,
    right_account    BOOLEAN      NOT NULL DEFAULT false,
    right_movement   BOOLEAN      NOT NULL DEFAULT false,
    right_inbox      BOOLEAN      NOT NULL DEFAULT false,
    right_attachment BOOLEAN      NOT NULL DEFAULT false,
    right_user       BOOLEAN      NOT NULL DEFAULT false
);

CREATE TABLE attachment
(
    id          SERIAL PRIMARY KEY,
    time_create BIGINT       NOT NULL,
    mime_type   VARCHAR(150) NOT NULL,
    sha512      VARCHAR(130) NOT NULL,
    file_size   INTEGER      NOT NULL,
    user_id     INTEGER      NOT NULL REFERENCES users ON DELETE RESTRICT
);

CREATE TABLE account
(
    id              SERIAL PRIMARY KEY,
    name            VARCHAR(50) NOT NULL,
    user_id         INTEGER     NOT NULL REFERENCES users ON DELETE CASCADE,
    time_create     BIGINT      NOT NULL,
    time_update     BIGINT      NOT NULL,
    default_account BOOLEAN     NOT NULL DEFAULT false
);

CREATE TABLE movement
(
    id            SERIAL PRIMARY KEY,
    account_id    INTEGER      NOT NULL REFERENCES account ON DELETE CASCADE,
    time          BIGINT       NOT NULL,
    label         VARCHAR(200) NOT NULL,
    attachment_id INT          REFERENCES attachment ON DELETE SET NULL,
    amount        REAL         NOT NULL,
    checked       BOOLEAN      NOT NULL DEFAULT false,
    time_create   BIGINT       NOT NULL,
    time_update   BIGINT       NOT NULL
);

CREATE TABLE inbox
(
    id            SERIAL PRIMARY KEY,
    attachment_id INTEGER NOT NULL REFERENCES attachment ON DELETE CASCADE,
    user_id       INTEGER NOT NULL REFERENCES users ON DELETE CASCADE,
    account_id    INTEGER REFERENCES account ON DELETE CASCADE,
    time_create   BIGINT  NOT NULL,
    time_update   BIGINT  NOT NULL
);