CREATE TABLE IF NOT EXISTS rh_owner (
  singleton_id TINYINT UNSIGNED NOT NULL DEFAULT 1,
  owner_id INT(10) UNSIGNED NOT NULL,
  granted_by INT(10) UNSIGNED NOT NULL,
  granted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (singleton_id),
  UNIQUE KEY owner_id (owner_id),
  CONSTRAINT rh_owner_user_fk FOREIGN KEY (owner_id) REFERENCES users(user_id) ON DELETE RESTRICT,
  CONSTRAINT rh_owner_granter_fk FOREIGN KEY (granted_by) REFERENCES users(user_id) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rh_role_audit (
  audit_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  target_user_id INT(10) UNSIGNED NOT NULL,
  old_role ENUM('owner','admin','member') DEFAULT NULL,
  new_role ENUM('owner','admin','member') NOT NULL,
  actor_id INT(10) UNSIGNED NOT NULL,
  reason VARCHAR(500) NOT NULL DEFAULT '',
  changed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (audit_id),
  KEY target_time (target_user_id, changed_at),
  KEY actor_time (actor_id, changed_at),
  CONSTRAINT rh_role_audit_target_fk FOREIGN KEY (target_user_id) REFERENCES users(user_id) ON DELETE RESTRICT,
  CONSTRAINT rh_role_audit_actor_fk FOREIGN KEY (actor_id) REFERENCES users(user_id) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
