-- 09: Legado Version20260425195500 — solo si ocr_document_creation_log existía sin dimensioner_measurement_log_id
SET @db := DATABASE();

SET @doc := (
  SELECT COUNT(*) FROM information_schema.TABLES
  WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'ocr_document_creation_log'
);
SET @dim := (
  SELECT COUNT(*) FROM information_schema.TABLES
  WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'dimensioner_measurement_log'
);
SET @col := (
  SELECT COUNT(*) FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'ocr_document_creation_log'
    AND COLUMN_NAME = 'dimensioner_measurement_log_id'
);
SET @sql := IF(@doc > 0 AND @dim > 0 AND @col = 0,
  'ALTER TABLE `ocr_document_creation_log` ADD COLUMN `dimensioner_measurement_log_id` BIGINT UNSIGNED DEFAULT NULL AFTER `user_id`',
  'SELECT ''skip legacy add column'' AS note');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @col2 := (
  SELECT COUNT(*) FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'ocr_document_creation_log'
    AND COLUMN_NAME = 'dimensioner_measurement_log_id'
);
SET @idx2 := (
  SELECT COUNT(*) FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'ocr_document_creation_log'
    AND INDEX_NAME = 'IDX_1D141786BA7F5D5D'
);
SET @sql := IF(@doc > 0 AND @dim > 0 AND @col2 > 0 AND @idx2 = 0,
  'CREATE INDEX `IDX_1D141786BA7F5D5D` ON `ocr_document_creation_log` (`dimensioner_measurement_log_id`)',
  'SELECT ''skip legacy index'' AS note');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @fk2 := (
  SELECT COUNT(*) FROM information_schema.TABLE_CONSTRAINTS
  WHERE CONSTRAINT_SCHEMA = @db AND TABLE_NAME = 'ocr_document_creation_log'
    AND CONSTRAINT_NAME = 'FK_1D141786BA7F5D5D' AND CONSTRAINT_TYPE = 'FOREIGN KEY'
);
SET @sql := IF(@doc > 0 AND @dim > 0 AND @col2 > 0 AND @fk2 = 0,
  'ALTER TABLE `ocr_document_creation_log` ADD CONSTRAINT `FK_1D141786BA7F5D5D` FOREIGN KEY (`dimensioner_measurement_log_id`) REFERENCES `dimensioner_measurement_log` (`id`) ON DELETE SET NULL',
  'SELECT ''skip legacy FK'' AS note');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
