/*
SETUP DATABASE ENVIROMENT FOR bbzw-horizon
INP21bL - M241/M245
*/

-- CREATE TABLES

CREATE TABLE "clients"(
    id INTEGER GENERATED BY DEFAULT AS IDENTITY,
    name VARCHAR(50),
    PRIMARY KEY(id)
);

CREATE TABLE "sensor_data"(
    id INTEGER GENERATED BY DEFAULT AS IDENTITY,
    timestamp TIMESTAMP,
    humidity DECIMAL(5,3),
    pressure DECIMAL(7,3),
    temperature DECIMAL(5,3),
    voc DECIMAL(5,3),
    gas DECIMAL(5,3),
    clientid INTEGER,
    PRIMARY KEY(id)
);

CREATE TABLE "user"(
    id INTEGER GENERATED BY DEFAULT AS IDENTITY,
    name VARCHAR(50),
    mail VARCHAR(150),
    password VARCHAR(250),
    api_access BOOLEAN,
    PRIMARY KEY(id)
);


CREATE TABLE "sessions"(
    id INTEGER GENERATED BY DEFAULT AS IDENTITY,
    token VARCHAR(96),
    validuntil DATE,
    userid INTEGER,
    PRIMARY KEY(id)
);


-- SET FOREIGN KEYS
ALTER TABLE "sensor_data" ADD FOREIGN KEY(clientid) REFERENCES "clients"(id);
ALTER TABLE "sessions" ADD FOREIGN KEY(userid) REFERENCES "user"(id);

-- SET DEFAULT VALUES
ALTER TABLE "user" ALTER COLUMN "api_access" SET DEFAULT False;
ALTER TABLE "sensor_data" ALTER COLUMN "timestamp" SET DEFAULT Now();
