CREATE TABLE IF NOT EXISTS audit_log (
  id INT AUTO_INCREMENT PRIMARY KEY,
  tenant_id INT NULL,
  actor_user_id INT NULL,
  action VARCHAR(60) NOT NULL,
  subject_type VARCHAR(60) NOT NULL,
  subject_id INT NULL,
  metadata_json TEXT NULL,
  ip VARCHAR(45) NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY idx_audit_log_tenant_created (tenant_id, created_at),
  KEY idx_audit_log_actor_user (actor_user_id),
  KEY idx_audit_log_subject (subject_type, subject_id),
  CONSTRAINT fk_audit_log_tenant
    FOREIGN KEY (tenant_id) REFERENCES tenants(id)
    ON DELETE CASCADE,
  CONSTRAINT fk_audit_log_actor_user
    FOREIGN KEY (actor_user_id) REFERENCES users(id)
    ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
