CREATE TYPE role AS ENUM ('staff', 'areamanager', 'admin');
CREATE TYPE function AS ENUM ('posten', 'wachhabender');

CREATE TABLE area
(
    id              SERIAL          PRIMARY KEY,
    name            TEXT            NOT NULL
);

INSERT INTO area (name) VALUES ('Leipzig Ost');

CREATE TABLE location
(
    id              SERIAL          PRIMARY KEY,
    name            TEXT            NOT NULL,
    areaId          INTEGER         NOT NULL REFERENCES area (id)
);

CREATE TABLE user_
(
    id                      SERIAL          PRIMARY KEY,
    name                    TEXT            NOT NULL,
    email                   TEXT            NOT NULL,
    password                TEXT            NOT NULL,
    salt                    TEXT            NOT NULL,
    role                    role            NOT NULL,
    function                function        NOT NULL,
    areaId                  INTEGER         NOT NULL REFERENCES area (id),
    locked                  BOOLEAN         NOT NULL DEFAULT false,
    lastLogin               TIMESTAMP WITH TIME ZONE,
    receiveNotifications    BOOLEAN         NOT NULL DEFAULT true
);

CREATE TABLE availabillity
(
    id                      SERIAL          PRIMARY KEY,
    userId                  INTEGER         NOT NULL REFERENCES user_ (id),
    date                    DATE            NOT NULL,
    startTime               TIME,
    endTime                 TIME,
    comment                 TEXT
);

CREATE TABLE event
(
    id                      SERIAL          PRIMARY KEY,
    date                    DATE            NOT NULL,
    startTime               TIME            NOT NULL,
    endTime                 TIME            NOT NULL,
    name                    TEXT            NOT NULL,
    locationId              INTEGER         NOT NULL REFERENCES location (id),
    voluntaryWachhabender   BOOLEAN         NOT NULL,
    amountOfPosten          SMALLINT        NOT NULL CHECK (amountOfPosten >= 0),
    clothing                TEXT            NOT NULL,
    canceled                BOOLEAN         NOT NULL DEFAULT false
);

CREATE TABLE assignement
(
    eventId                 INTEGER         REFERENCES event (id),
    availabillityId         INTEGER         REFERENCES availabillity (id),
    function                function        NOT NULL,
    startTime               TIME,
    endTime                 TIME,
    PRIMARY KEY (eventId, availabillityId)
);

CREATE TABLE vehicle
(
    id                      SERIAL          PRIMARY KEY,
    radioCallName           TEXT            NOT NULL,
    station                 TEXT            NOT NULL
);

CREATE TABLE vehicleassignement
(
    eventId                 INTEGER         REFERENCES event (id),
    vehicleId               INTEGER         REFERENCES vehicle (id),
    PRIMARY KEY (eventId, vehicleId)
);
