CREATE TABLE IF NOT EXISTS "User" (
        id SERIAL PRIMARY KEY,
        username VARCHAR(255) NOT NULL UNIQUE,
        password VARCHAR(255),
        admin BOOLEAN NOT NULL DEFAULT FALSE,
        realname VARCHAR(255)
);

CREATE TYPE sasl_mechanism AS ENUM ('PLAIN', 'EXTERNAL');

CREATE TABLE IF NOT EXISTS "Network" (
        id SERIAL PRIMARY KEY,
        name VARCHAR(255),
        "user" INTEGER NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
        addr VARCHAR(255) NOT NULL,
        nick VARCHAR(255),
        username VARCHAR(255),
        realname VARCHAR(255),
        pass VARCHAR(255),
        connect_commands VARCHAR(1023),
        sasl_mechanism sasl_mechanism,
        sasl_plain_username VARCHAR(255),
        sasl_plain_password VARCHAR(255),
        sasl_external_cert BYTEA,
        sasl_external_key BYTEA,
        enabled BOOLEAN NOT NULL DEFAULT TRUE,
        UNIQUE("user", addr, nick),
        UNIQUE("user", name)
);
CREATE TABLE IF NOT EXISTS "Channel" (
        id SERIAL PRIMARY KEY,
        network INTEGER NOT NULL REFERENCES "Network"(id) ON DELETE CASCADE,
        name VARCHAR(255) NOT NULL,
        key VARCHAR(255),
        detached BOOLEAN NOT NULL DEFAULT FALSE,
        detached_internal_msgid VARCHAR(255),
        relay_detached INTEGER NOT NULL DEFAULT 0,
        reattach_on INTEGER NOT NULL DEFAULT 0,
        detach_after INTEGER NOT NULL DEFAULT 0,
        detach_on INTEGER NOT NULL DEFAULT 0,
        UNIQUE(network, name)
);
CREATE TABLE IF NOT EXISTS "DeliveryReceipt" (
        id SERIAL PRIMARY KEY,
        network INTEGER NOT NULL REFERENCES "Network"(id) ON DELETE CASCADE,
        target VARCHAR(255) NOT NULL,
        client VARCHAR(255) NOT NULL DEFAULT '',
        internal_msgid VARCHAR(255) NOT NULL,
        UNIQUE(network, target, client)
);
CREATE TABLE IF NOT EXISTS "ReadReceipt" (
        id SERIAL PRIMARY KEY,
        network INTEGER NOT NULL REFERENCES "Network"(id) ON DELETE CASCADE,
        target VARCHAR(255) NOT NULL,
        timestamp TIMESTAMP WITH TIME ZONE NOT NULL,
        UNIQUE(network, target)
);

