CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated = now();
    RETURN NEW;
END; $$ language 'plpgsql';

CREATE TABLE users (
        id SERIAL PRIMARY KEY,
        name text NOT NULL UNIQUE,
        updated timestamp DEFAULT current_timestamp,
        created timestamp DEFAULT current_timestamp
);

CREATE TRIGGER update_users BEFORE UPDATE ON users FOR EACH ROW EXECUTE PROCEDURE  update_modified_column();

CREATE TABLE tokens (
        id SERIAL,
        value text NOT NULL UNIQUE,
        users_id integer REFERENCES users (id) ON DELETE CASCADE,
        updated timestamp DEFAULT current_timestamp,
        created timestamp DEFAULT current_timestamp
);

CREATE TRIGGER update_tokens BEFORE UPDATE ON tokens FOR EACH ROW EXECUTE PROCEDURE  update_modified_column();

CREATE TABLE shows (
        id SERIAL PRIMARY KEY,
        imdbid text NOT NULL UNIQUE,
        title text NOT NULL,
        updated timestamp DEFAULT current_timestamp,
        created timestamp DEFAULT current_timestamp
);

CREATE TRIGGER update_shows BEFORE UPDATE ON shows FOR EACH ROW EXECUTE PROCEDURE  update_modified_column();

CREATE TABLE episodes (
        id SERIAL PRIMARY KEY,
        shows_id integer REFERENCES shows (id) ON DELETE CASCADE,
        title text NOT NULL,
        season integer NOT NULL,
        episode integer NOT NULL,
        updated timestamp DEFAULT current_timestamp,
        created timestamp DEFAULT current_timestamp
);

CREATE TRIGGER update_episodes BEFORE UPDATE ON episodes FOR EACH ROW EXECUTE PROCEDURE  update_modified_column();

CREATE TABLE shows_tracked (
        shows_id integer NOT NULL REFERENCES shows (id) ON DELETE CASCADE,
        users_id integer NOT NULL REFERENCES users (id) ON DELETE CASCADE,
        season integer NOT NULL,
        episode integer NOT NULL
);
