CREATE TABLE IF NOT EXISTS operational_agent_routing_decisions (
  id CHAR(36) NOT NULL PRIMARY KEY,
  law_firm_id CHAR(36) NOT NULL,
  ai_run_id CHAR(36) NULL,
  source_entity_type VARCHAR(50) NOT NULL,
  source_entity_id CHAR(36) NULL,
  operation_type VARCHAR(50) NOT NULL,
  stage_code VARCHAR(80) NOT NULL,
  selected_agent_scope VARCHAR(50) NOT NULL,
  selected_agent_key VARCHAR(120) NOT NULL,
  selected_agent_name VARCHAR(180) NOT NULL,
  decision_json JSON NOT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY idx_operational_agent_routing_law_firm (law_firm_id, created_at),
  KEY idx_operational_agent_routing_ai_run (ai_run_id, created_at),
  KEY idx_operational_agent_routing_source (source_entity_type, source_entity_id, created_at),
  KEY idx_operational_agent_routing_stage (operation_type, stage_code, created_at),
  CONSTRAINT fk_operational_agent_routing_law_firm
    FOREIGN KEY (law_firm_id) REFERENCES law_firms (id),
  CONSTRAINT fk_operational_agent_routing_ai_run
    FOREIGN KEY (ai_run_id) REFERENCES ai_runs (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
