CREATE TABLE applied (
    channel VARCHAR NOT NULL,
    ts VARCHAR NOT NULL,
    name VARCHAR NOT NULL,
    color VARCHAR NOT NULL DEFAULT 'yellow',
    PRIMARY KEY (channel, ts, name)
);

CREATE TABLE reaction_log (
    userid VARCHAR NOT NULL,
    channel VARCHAR NOT NULL,
    ts VARCHAR NOT NULL,
    event_type VARCHAR NOT NULL,
    event_ts VARCHAR NOT NULL,
    reaction VARCHAR NOT NULL
);
CREATE INDEX lookup_idx ON reaction_log USING btree (channel, ts, userid, reaction, event_ts DESC);

CREATE TABLE message_sheet_link (
    channel VARCHAR NOT NULL,
    ts VARCHAR NOT NULL,
    sheet_title VARCHAR NOT NULL,
    PRIMARY KEY (channel, ts)
);

CREATE TABLE users_nagged (
    userid VARCHAR NOT NULL,
    last_nag TIMESTAMP WITH TIME ZONE NOT NULL,
    PRIMARY KEY (userid)
);

CREATE VIEW current_reactions AS
  SELECT userid, channel, ts, reaction
    FROM ( SELECT DISTINCT ON (channel, ts, userid, reaction)
               userid, channel, ts, event_type, event_ts, reaction
           FROM reaction_log ORDER BY channel, ts, userid, reaction, event_ts DESC ) t1
  WHERE event_type = 'reaction_added';

GRANT SELECT,UPDATE,INSERT,DELETE ON TABLE applied TO skvidarlang;
GRANT SELECT,INSERT ON TABLE reaction_log TO skvidarlang;
GRANT SELECT ON TABLE current_reactions TO skvidarlang;
GRANT SELECT,UPDATE,INSERT ON TABLE message_sheet_link TO skvidarlang;
GRANT SELECT,INSERT ON TABLE users_nagged TO skvidarlang;
