-- audit_request / audit_event / audit_diff
CREATE TABLE IF NOT EXISTS wp_audit_request (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  request_id VARCHAR(64) NOT NULL UNIQUE,
  started_at DATETIME NOT NULL,
  ended_at DATETIME NULL,
  status_code INT NULL,
  user_id BIGINT UNSIGNED NULL,
  session_id VARCHAR(128) NULL,
  contrato_id INT NULL,
  method VARCHAR(10) NULL,
  url TEXT NULL,
  referer TEXT NULL,
  ip VARCHAR(45) NULL,
  user_agent TEXT NULL,
  app_version VARCHAR(32) NULL,
  extra_json LONGTEXT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS wp_audit_event (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  request_id VARCHAR(64) NOT NULL,
  happened_at DATETIME NOT NULL,
  actor_user_id BIGINT UNSIGNED NULL,
  action VARCHAR(32) NOT NULL,
  table_name VARCHAR(128) NULL,
  record_id BIGINT UNSIGNED NULL,
  message TEXT NULL,
  severity TINYINT NOT NULL DEFAULT 0,
  ip VARCHAR(45) NULL,
  user_agent TEXT NULL,
  url TEXT NULL,
  contrato_id INT NULL,
  meta_json LONGTEXT NULL,
  KEY idx_request (request_id),
  KEY idx_table (table_name),
  KEY idx_actor (actor_user_id),
  KEY idx_contrato (contrato_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS wp_audit_diff (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  event_id BIGINT UNSIGNED NOT NULL,
  field VARCHAR(128) NOT NULL,
  old_value TEXT NULL,
  new_value TEXT NULL,
  change_json LONGTEXT NULL,
  KEY idx_event (event_id),
  CONSTRAINT fk_audit_diff_event FOREIGN KEY (event_id) REFERENCES wp_audit_event(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;