-- DBN DMS migration 005 — audit log
-- Powers the "Recent activity" widget on the dashboard overview.

CREATE TABLE IF NOT EXISTS client_document_audit (
  id          BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  client_id   INT UNSIGNED NOT NULL,
  user_id     INT UNSIGNED NULL,
  document_id INT UNSIGNED NULL,
  folder_id   INT UNSIGNED NULL,
  action      VARCHAR(40) NOT NULL
              COMMENT 'upload|view|edit|move|rename|version|delete|restore|share|download|search|chat|category|tag',
  details     JSON NULL,
  ip_addr     VARCHAR(45) NULL,
  created_at  DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY idx_client_time (client_id, created_at),
  KEY idx_doc         (document_id),
  KEY idx_user_time   (user_id, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  COMMENT='Append-only audit trail for DMS activity. Document/folder FKs intentionally not enforced — keep history after deletes.';
