
CREATE TABLE IF NOT EXISTS user (
    username varchar(255) NOT NULL PRIMARY KEY,
    password text NOT NULL,
    user_role text NOT NULL DEFAULT 'Regular' CHECK (user_role IN ('regular', 'admin'))
);

CREATE TABLE IF NOT EXISTS user_session (
    id UUID NOT NULL PRIMARY KEY DEFAULT gen_random_uuid(),
    token text NOT NULL,
    user varchar(255) NOT NULL,
    FOREIGN KEY(user) REFERENCES user(username)
);

CREATE TABLE IF NOT EXISTS artist (
    id UUID NOT NULL PRIMARY KEY DEFAULT gen_random_uuid(),
    name text NOT NULL
);

CREATE TABLE IF NOT EXISTS album (
    id UUID NOT NULL PRIMARY KEY DEFAULT gen_random_uuid(),
    title text NOT NULL,
    artist UUID
    FOREIGN KEY(artist) REFERENCES artist(id)
);

CREATE TABLE IF NOT EXISTS track (
    id UUID NOT NULL PRIMARY KEY DEFAULT gen_random_uuid(),
    path text NOT NULL,
    title text,
    date_added timestampz NOT NULL DEFAULT current_timestamp,
    album UUID,
    artist UUID,
    meta jsonb,
    FOREIGN KEY(album) REFERENCES album(id),
    FOREIGN KEY(artist) REFERENCES artist(id)
);

CREATE TABLE IF NOT EXISTS events (
    id UUID NOT NULL PRIMARY KEY DEFAULT gen_random_uuid(),
    time timestampz NOT NULL DEFAULT current_timestamp,
    kind text CHECK (kind IN ('play', 'played', 'stop')),
    user VARCHAR(255) NOT NULL,
    track UUID NOT NULL,
    FOREIGN KEY(user) REFERENCES user(username),
    FOREIGN KEY(track) REFERENCES track(id)
);

SELECT create_hypertable('events', by_range('time'));
