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 tokens
(
    id             SERIAL PRIMARY KEY,
    name           VARCHAR(150) NOT NULL,
    time_create    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      NOT NULL,
    ip_net         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_file     BOOLEAN      NOT NULL DEFAULT false,
    right_auth     BOOLEAN      NOT NULL DEFAULT false,
    right_stats    BOOLEAN      NOT NULL DEFAULT false
);

CREATE TABLE files
(
    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,
    file_name   VARCHAR(150) NOT NULL,
    user_id     INTEGER      NOT NULL REFERENCES users ON DELETE SET NULL
);

CREATE TABLE accounts
(
    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,
    type            VARCHAR(1)  NOT NULL DEFAULT 'C',
    default_account BOOLEAN     NOT NULL DEFAULT false
);

CREATE TABLE movements
(
    id          SERIAL PRIMARY KEY,
    account_id  INTEGER      NOT NULL REFERENCES accounts ON DELETE CASCADE,
    time        BIGINT       NOT NULL,
    label       VARCHAR(200) NOT NULL,
    file_id     INT REFERENCES files ON DELETE RESTRICT,
    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,
    file_id     INTEGER NOT NULL REFERENCES files ON DELETE RESTRICT,
    user_id     INTEGER NOT NULL REFERENCES users ON DELETE CASCADE,
    account_id  INTEGER REFERENCES accounts ON DELETE CASCADE,
    time_create BIGINT  NOT NULL,
    time_update BIGINT  NOT NULL
);