CREATE TABLE user(
    [name] TEXT NOT NULL,
    [password] TEXT NOT NULL,
    [is_admin] TINYINT NOT NULL CHECK(is_admin = 1 OR is_admin = 0),
    [salt] INTEGER NOT NULL,

    PRIMARY KEY (name)
);

CREATE TABLE token(
    [user] TEXT NOT NULL,
    [token] TEXT UNIQUE NOT NULL,
    [token_expire_on] BIGINT NOT NULL,
    [ua] TEXT NOT NULL,
    [ip] TEXT NOT NULL,

    FOREIGN KEY (user) REFERENCES user(name) ON DELETE CASCADE
);

CREATE TABLE collection(
    [uuid] TEXT NOT NULL,
    [name] TEXT NOT NULL,
    [user] TEXT NOT NULL,
    [last_change] TEXT NOT NULL,

    PRIMARY KEY (uuid),
    FOREIGN KEY (user) REFERENCES user(name) ON DELETE CASCADE
);

CREATE TABLE share(
    [uuid] TEXT NOT NULL,
    [target] TEXT NOT NULL,

    FOREIGN KEY (uuid) REFERENCES collection(uuid) ON DELETE CASCADE
    FOREIGN KEY (target) REFERENCES user(name) ON DELETE CASCADE
);

CREATE TABLE calendar(
    [uuid] TEXT NOT NULL,
    [belong_to] TEXT NOT NULL,

    [title] TEXT NOT NULL,
    [description] TEXT NOT NULL,
    [last_change] TEXT NOT NULL,

    [event_date_time_start] BIGINT NOT NULL,
    [event_date_time_end] BIGINT NOT NULL,
    [timezone_offset] INT NOT NULL,
    
    [loop_rules] TEXT NOT NULL,
    [loop_date_time_start] BIGINT NOT NULL,
    [loop_date_time_end] BIGINT NOT NULL,

    PRIMARY KEY (uuid),
    FOREIGN KEY (belong_to) REFERENCES collection(uuid) ON DELETE CASCADE
);

CREATE TABLE todo(
    [uuid] TEXT NOT NULL,
    [belong_to] TEXT NOT NULL,

    [data] TEXT NOT NULL,
    [last_change] TEXT NOT NULL,

    PRIMARY KEY (uuid),
    FOREIGN KEY (belong_to) REFERENCES user(name) ON DELETE CASCADE
);