-- 04: Todas las FK de ocr_customer_match_log (ejecutar tras 02 y 03)
SET @db := DATABASE();
SET @fk := (
    SELECT COUNT(*)
    FROM information_schema.TABLE_CONSTRAINTS
    WHERE CONSTRAINT_SCHEMA = @db
      AND TABLE_NAME = 'ocr_customer_match_log'
      AND CONSTRAINT_NAME = 'FK_8D61DAD318C8CC62'
      AND CONSTRAINT_TYPE = 'FOREIGN KEY'
  );
SET @sql := IF(
    @fk = 0,
    'ALTER TABLE `ocr_customer_match_log` ADD CONSTRAINT `FK_8D61DAD318C8CC62` FOREIGN KEY (`maincompany_id`) REFERENCES `maincompany` (`id`)',
    'SELECT ''skip FK_8D61DAD318C8CC62'' AS note'
  );
PREPARE stmt
FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @fk := (
    SELECT COUNT(*)
    FROM information_schema.TABLE_CONSTRAINTS
    WHERE CONSTRAINT_SCHEMA = @db
      AND TABLE_NAME = 'ocr_customer_match_log'
      AND CONSTRAINT_NAME = 'FK_8D61DAD3598DEE3D'
      AND CONSTRAINT_TYPE = 'FOREIGN KEY'
  );
SET @sql := IF(
    @fk = 0,
    'ALTER TABLE `ocr_customer_match_log` ADD CONSTRAINT `FK_8D61DAD3598DEE3D` FOREIGN KEY (`matched_customer_id`) REFERENCES `customer` (`id`)',
    'SELECT ''skip FK_8D61DAD3598DEE3D'' AS note'
  );
PREPARE stmt
FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @fk := (
    SELECT COUNT(*)
    FROM information_schema.TABLE_CONSTRAINTS
    WHERE CONSTRAINT_SCHEMA = @db
      AND TABLE_NAME = 'ocr_customer_match_log'
      AND CONSTRAINT_NAME = 'FK_8D61DAD3295973C3'
      AND CONSTRAINT_TYPE = 'FOREIGN KEY'
  );
SET @sql := IF(
    @fk = 0,
    'ALTER TABLE `ocr_customer_match_log` ADD CONSTRAINT `FK_8D61DAD3295973C3` FOREIGN KEY (`matched_agency_customer_id`) REFERENCES `customer` (`id`)',
    'SELECT ''skip FK_8D61DAD3295973C3'' AS note'
  );
PREPARE stmt
FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @fk := (
    SELECT COUNT(*)
    FROM information_schema.TABLE_CONSTRAINTS
    WHERE CONSTRAINT_SCHEMA = @db
      AND TABLE_NAME = 'ocr_customer_match_log'
      AND CONSTRAINT_NAME = 'FK_8D61DAD373491C0A'
      AND CONSTRAINT_TYPE = 'FOREIGN KEY'
  );
SET @sql := IF(
    @fk = 0,
    'ALTER TABLE `ocr_customer_match_log` ADD CONSTRAINT `FK_8D61DAD373491C0A` FOREIGN KEY (`matched_carrier_customer_id`) REFERENCES `customer` (`id`)',
    'SELECT ''skip FK_8D61DAD373491C0A'' AS note'
  );
PREPARE stmt
FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @fk := (
    SELECT COUNT(*)
    FROM information_schema.TABLE_CONSTRAINTS
    WHERE CONSTRAINT_SCHEMA = @db
      AND TABLE_NAME = 'ocr_customer_match_log'
      AND CONSTRAINT_NAME = 'FK_8D61DAD372B5D9E2'
      AND CONSTRAINT_TYPE = 'FOREIGN KEY'
  );
SET @sql := IF(
    @fk = 0,
    'ALTER TABLE `ocr_customer_match_log` ADD CONSTRAINT `FK_8D61DAD372B5D9E2` FOREIGN KEY (`matched_rule_id`) REFERENCES `ocr_customer_match_rule` (`id`)',
    'SELECT ''skip FK_8D61DAD372B5D9E2'' AS note'
  );
PREPARE stmt
FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
