begin transaction;

create table newsgroup (
    id          INTEGER PRIMARY KEY NOT NULL,
    created_on  DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    created_by  TEXT NOT NULL,
    name        TEXT NOT NULL,
    description TEXT NOT NULL,
    writable    BOOLEAN NOT NULL DEFAULT FALSE
);

create table message (
    id            INTEGER PRIMARY KEY NOT NULL,
    created_on    DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    message_id    TEXT NOT NULL UNIQUE,
    reference_ids TEXT,
    sender        TEXT NOT NULL,
    subject       TEXT NOT NULL,
    content       TEXT NOT NULL
);

create table newsgroup_message (
    newsgroup_id INTEGER NOT NULL,
    message_id INTEGER NOT NULL,

    FOREIGN KEY(newsgroup_id) REFERENCES newsgroup(id),
    FOREIGN KEY(message_id)   REFERENCES message(id)
);

create unique index newsgroup_message_newsgroup_id_idx on newsgroup_message (
    newsgroup_id, message_id
);

create table server_permission (
    id   INTEGER PRIMARY KEY NOT NULL,
    name TEXT NOT NULL
);

insert into server_permission values
    (1, 'READ'),
    (2, 'POST'),
    (3, 'KILL');

create table server_user (
    id       INTEGER PRIMARY KEY NOT NULL,
    active   BOOLEAN NOT NULL DEFAULT TRUE,
    username TEXT NOT NULL,
    password TEXT,
    fullname TEXT,
    mail     TEXT NOT NULL
);

create table server_user_permission (
    permission_id INTEGER NOT NULL,
    user_id       INTEGER NOT NULL,

    UNIQUE(permission_id, user_id),
    FOREIGN KEY(permission_id) REFERENCES server_permission(id),
    FOREIGN KEY(user_id)       REFERENCES server_user(id)
);

commit;
