ALTER TABLE mra_eis_configurations
  ADD COLUMN IF NOT EXISTS offline_time_threshold_hours DECIMAL(10,4) DEFAULT NULL AFTER standard_vat_percentage,
  ADD COLUMN IF NOT EXISTS offline_started_at DATETIME DEFAULT NULL AFTER offline_time_threshold_hours,
  ADD COLUMN IF NOT EXISTS last_successful_eis_connection_at DATETIME DEFAULT NULL AFTER offline_started_at,
  ADD COLUMN IF NOT EXISTS last_eis_sync_at DATETIME DEFAULT NULL AFTER last_successful_eis_connection_at,
  ADD COLUMN IF NOT EXISTS eis_connection_status ENUM('unknown','online','offline') NOT NULL DEFAULT 'unknown' AFTER last_eis_sync_at;

INSERT INTO mra_eis_configurations (
  terminal_local_id,
  global_config_version,
  taxpayer_config_version,
  terminal_config_version,
  standard_vat_percentage,
  global_configuration_json,
  taxpayer_configuration_json,
  terminal_configuration_json,
  tax_rates_json,
  levy_rates_json,
  source_response_json,
  source_hash,
  mra_synced_at
)
SELECT
  t.id,
  COALESCE(t.global_config_version, 1),
  COALESCE(t.taxpayer_config_version, 1),
  COALESCE(t.terminal_config_version, 1),
  NULL,
  COALESCE(JSON_EXTRACT(t.activation_response, '$.data.configuration.globalConfiguration'), JSON_OBJECT()),
  COALESCE(JSON_EXTRACT(t.activation_response, '$.data.configuration.taxpayerConfiguration'), JSON_OBJECT()),
  COALESCE(JSON_EXTRACT(t.activation_response, '$.data.configuration.terminalConfiguration'), JSON_OBJECT()),
  COALESCE(JSON_EXTRACT(t.activation_response, '$.data.configuration.globalConfiguration.taxRates'), JSON_ARRAY()),
  COALESCE(JSON_EXTRACT(t.activation_response, '$.data.configuration.globalConfiguration.levyRates'), JSON_ARRAY()),
  t.activation_response,
  SHA2(t.activation_response, 256),
  UTC_TIMESTAMP()
FROM mra_eis_terminals t
WHERE t.activation_response IS NOT NULL
  AND JSON_VALID(t.activation_response)
  AND JSON_EXTRACT(t.activation_response, '$.data.configuration.terminalConfiguration') IS NOT NULL
ON DUPLICATE KEY UPDATE terminal_local_id = VALUES(terminal_local_id);

UPDATE mra_eis_configurations
SET offline_time_threshold_hours = CAST(
  JSON_UNQUOTE(JSON_EXTRACT(terminal_configuration_json, '$.offlineLimit.maxTransactionAgeInHours')) AS DECIMAL(10,4)
)
WHERE JSON_VALID(terminal_configuration_json)
  AND JSON_EXTRACT(terminal_configuration_json, '$.offlineLimit.maxTransactionAgeInHours') IS NOT NULL;

ALTER TABLE mra_eis_outbox
  MODIFY COLUMN status ENUM('pending','ready','blocked','processing','submitted','failed') NOT NULL DEFAULT 'pending',
  ADD COLUMN IF NOT EXISTS lock_token CHAR(36) DEFAULT NULL AFTER status,
  ADD COLUMN IF NOT EXISTS locked_at DATETIME DEFAULT NULL AFTER lock_token,
  ADD KEY IF NOT EXISTS idx_mra_eis_outbox_claim (status, locked_at, created_at);
