ALTER TABLE mra_eis_terminals
  ADD COLUMN IF NOT EXISTS site_id VARCHAR(80) DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS global_config_version INT NOT NULL DEFAULT 1,
  ADD COLUMN IF NOT EXISTS taxpayer_config_version INT NOT NULL DEFAULT 1,
  ADD COLUMN IF NOT EXISTS terminal_config_version INT NOT NULL DEFAULT 1;

CREATE TABLE IF NOT EXISTS mra_eis_outbox (
  id INT AUTO_INCREMENT PRIMARY KEY,
  entity_type VARCHAR(40) NOT NULL,
  source_table VARCHAR(80) NOT NULL,
  source_id VARCHAR(120) DEFAULT NULL,
  source_key VARCHAR(160) NOT NULL,
  branch_id INT DEFAULT NULL,
  terminal_local_id INT DEFAULT NULL,
  endpoint VARCHAR(255) NOT NULL,
  payload_json MEDIUMTEXT NOT NULL,
  status ENUM('pending','ready','blocked','submitted','failed') NOT NULL DEFAULT 'pending',
  attempts INT NOT NULL DEFAULT 0,
  http_status INT DEFAULT NULL,
  response_body MEDIUMTEXT NULL,
  mra_reference VARCHAR(255) DEFAULT NULL,
  validation_url TEXT NULL,
  local_audit_json MEDIUMTEXT NULL,
  last_error TEXT NULL,
  created_by INT DEFAULT NULL,
  submitted_at DATETIME DEFAULT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uniq_mra_eis_outbox_source (entity_type, source_key),
  KEY idx_mra_eis_outbox_status (status),
  KEY idx_mra_eis_outbox_branch (branch_id),
  KEY idx_mra_eis_outbox_terminal (terminal_local_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

ALTER TABLE mra_eis_outbox
  ADD COLUMN IF NOT EXISTS validation_url TEXT NULL,
  ADD COLUMN IF NOT EXISTS local_audit_json MEDIUMTEXT NULL;

CREATE TABLE IF NOT EXISTS mra_eis_compliance_events (
  id INT AUTO_INCREMENT PRIMARY KEY,
  outbox_id INT DEFAULT NULL,
  entity_type VARCHAR(40) NOT NULL,
  source_key VARCHAR(160) NOT NULL,
  event_type VARCHAR(80) NOT NULL,
  message TEXT NULL,
  payload_snapshot MEDIUMTEXT NULL,
  created_by INT DEFAULT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY idx_mra_eis_events_outbox (outbox_id),
  KEY idx_mra_eis_events_source (entity_type, source_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
