BEGIN;

CREATE TABLE logging_guilds(
  guildid BIGINT PRIMARY KEY,
  webhook_url TEXT,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  _timestamp TIMESTAMPTZ DEFAULT NOW()
);

CREATE TRIGGER logging_guilds_timestamp BEFORE UPDATE ON logging_guilds
  FOR EACH ROW EXECUTE FUNCTION update_timestamp_column();


CREATE TABLE logged_messages(
  messageid BIGINT PRIMARY KEY,
  guildid BIGINT NOT NULL REFERENCES logging_guilds ON DELETE CASCADE,
  channelid BIGINT NOT NULL,
  userid BIGINT NOT NULL,
  created_at TIMESTAMPTZ NOT NULL,
  deleted_at TIMESTAMPTZ,
  _timestamp TIMESTAMPTZ DEFAULT NOW()
);

CREATE TRIGGER logged_messages_timestamp BEFORE UPDATE ON logged_messages
  FOR EACH ROW EXECUTE FUNCTION update_timestamp_column();

CREATE TABLE message_states(
  stateid INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
  messageid BIGINT NOT NULL REFERENCES logged_messages ON DELETE CASCADE,
  content TEXT NOT NULL,
  embeds_raw TEXT,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX message_states_messageid ON message_states (messageid);

CREATE TABLE logged_attachments(
  attachment_id BIGINT PRIMARY KEY,
  proxy_url TEXT NOT NULL,
  url TEXT NOT NULL,
  content_type TEXT NOT NULL,
  filesize INTEGER NOT NULL,
  filename TEXT NOT NULL,
  permalink TEXT,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE logged_messages_attachments(
  stateid INTEGER NOT NULL REFERENCES message_states(stateid) ON DELETE CASCADE,
  attachment_id BIGINT NOT NULL REFERENCES logged_attachments(attachment_id) ON DELETE CASCADE
);
CREATE INDEX logged_messages_attachments_stateid ON logged_messages_attachments (stateid);

COMMIT;
