-- Feed cooling period: track what each user has seen
CREATE TABLE IF NOT EXISTS user_feed_impressions (
  user_id  uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  post_id  uuid NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
  shown_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (user_id, post_id)
);
CREATE INDEX IF NOT EXISTS idx_feed_impressions_user_time ON user_feed_impressions(user_id, shown_at);

-- E2EE group key management
ALTER TABLE groups ADD COLUMN IF NOT EXISTS key_rotation_needed bool NOT NULL DEFAULT false;
ALTER TABLE groups ADD COLUMN IF NOT EXISTS key_version int NOT NULL DEFAULT 1;

CREATE TABLE IF NOT EXISTS group_member_keys (
  group_id      uuid NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
  user_id       uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  key_version   int NOT NULL DEFAULT 1,
  encrypted_key text NOT NULL,
  device_key_id text,
  updated_at    timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (group_id, user_id, key_version)
);
CREATE INDEX IF NOT EXISTS idx_group_member_keys_group ON group_member_keys(group_id, key_version);
