--creating system table
CREATE TABLE IF NOT EXISTS system (
    `key` VARCHAR(32) PRIMARY KEY,
    `value` TEXT
);

--creating roles table
CREATE TABLE IF NOT EXISTS roles (
    `id` INTEGER UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    `name` VARCHAR(256) UNIQUE NOT NULL,
    `color` INTEGER UNSIGNED DEFAULT 0
);

--creating accounts table
CREATE TABLE IF NOT EXISTS accounts (
    `id` INTEGER UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    `login` VARCHAR(256) UNIQUE NOT NULL,
    `nick` VARCHAR(256),
    `type` INTEGER UNSIGNED NOT NULL,
    `password` VARCHAR(128),
    `created` TIMESTAMP DEFAULT UTC_TIMESTAMP()
);

--creating role bindings table
CREATE TABLE IF NOT EXISTS roleBindings (
    `account` INTEGER UNSIGNED NOT NULL,
    `role` INTEGER UNSIGNED NOT NULL,

    PRIMARY KEY (account, role),
    FOREIGN KEY (account) REFERENCES accounts(id),
    FOREIGN KEY (role) REFERENCES roles(id)
);

--creating sessings table
CREATE TABLE IF NOT EXISTS sessions (
    `id` INTEGER AUTO_INCREMENT PRIMARY KEY,
    `owner` INTEGER UNSIGNED NOT NULL,
    `started` TIMESTAMP DEFAULT UTC_TIMESTAMP(),
    `latest` TIMESTAMP DEFAULT UTC_TIMESTAMP(),
    `access` CHAR(32) NOT NULL UNIQUE,
    `renew` CHAR(32),
    `persist` BOOLEAN NOT NULL,
    `device` TEXT,

    FOREIGN KEY (owner) REFERENCES accounts(id)
);

--creating defailt roles
INSERT IGNORE INTO roles (`name`)
VALUES ('root'),
       ('default');

--inserting initial version
INSERT INTO system (`key`, `value`) VALUES ('version', '0');

--recording initial time
INSERT INTO system (`key`, `value`) VALUES ('created', UTC_TIMESTAMP());
