-- Make the local-first FindS synchronization schema safe for existing databases.

SET @ddl = IF(
  (SELECT COUNT(1) FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'fence' AND COLUMN_NAME = 'org_code') = 0,
  'ALTER TABLE `fence` ADD COLUMN `org_code` varchar(64) DEFAULT NULL COMMENT ''所属公司编码'' AFTER `corpinfo_name`',
  'DO 0'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl = IF(
  (SELECT COUNT(1) FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'fence' AND COLUMN_NAME = 'org_name') = 0,
  'ALTER TABLE `fence` ADD COLUMN `org_name` varchar(255) DEFAULT NULL COMMENT ''所属公司名称'' AFTER `org_code`',
  'DO 0'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl = IF(
  (SELECT COUNT(1) FROM information_schema.STATISTICS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'fence' AND INDEX_NAME = 'idx_org_code') = 0,
  'ALTER TABLE `fence` ADD KEY `idx_org_code` (`org_code`)',
  'DO 0'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

UPDATE `alarm_record`
SET `corpinfo_id` = 0
WHERE `finds_alarm_id` IS NOT NULL AND `corpinfo_id` IS NULL;

CREATE TEMPORARY TABLE `tmp_alarm_record_keeper` AS
SELECT `corpinfo_id`, `finds_alarm_id`, MAX(`id`) AS `keep_id`
FROM `alarm_record`
WHERE `finds_alarm_id` IS NOT NULL
GROUP BY `corpinfo_id`, `finds_alarm_id`
HAVING COUNT(1) > 1;

UPDATE `alarm_record_target` target
JOIN `alarm_record` duplicate_record ON duplicate_record.`id` = target.`alarm_record_id`
JOIN `tmp_alarm_record_keeper` keeper
  ON keeper.`corpinfo_id` = duplicate_record.`corpinfo_id`
 AND keeper.`finds_alarm_id` = duplicate_record.`finds_alarm_id`
SET target.`alarm_record_id` = keeper.`keep_id`
WHERE duplicate_record.`id` <> keeper.`keep_id`;

UPDATE `alarm_dispose_record` dispose_record
JOIN `alarm_record` duplicate_record ON duplicate_record.`id` = dispose_record.`alarm_record_id`
JOIN `tmp_alarm_record_keeper` keeper
  ON keeper.`corpinfo_id` = duplicate_record.`corpinfo_id`
 AND keeper.`finds_alarm_id` = duplicate_record.`finds_alarm_id`
SET dispose_record.`alarm_record_id` = keeper.`keep_id`
WHERE duplicate_record.`id` <> keeper.`keep_id`;

DELETE duplicate_record
FROM `alarm_record` duplicate_record
JOIN `tmp_alarm_record_keeper` keeper
  ON keeper.`corpinfo_id` = duplicate_record.`corpinfo_id`
 AND keeper.`finds_alarm_id` = duplicate_record.`finds_alarm_id`
WHERE duplicate_record.`id` <> keeper.`keep_id`;

DROP TEMPORARY TABLE `tmp_alarm_record_keeper`;

SET @ddl = IF(
  (SELECT COUNT(1) FROM information_schema.STATISTICS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'alarm_record'
     AND INDEX_NAME = 'uk_corpinfo_finds_alarm') = 0,
  'ALTER TABLE `alarm_record` ADD UNIQUE KEY `uk_corpinfo_finds_alarm` (`corpinfo_id`, `finds_alarm_id`)',
  'DO 0'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
