-- 1.0.309：WP9 S5 — S5 生产领料切源到 165 + 本库历史 SM 打 AIDOP_LEGACY
-- 1) NbrMaster.source_system 列（本库历史标记用）
-- 2) 存量 Type=SM 标记 AIDOP_LEGACY（D8-A）
-- 3) 启用 S5_PRODUCTION_ISSUE_MASTER_SQLSERVER，停用本库 S5_PRODUCTION_ISSUE_MASTER
-- 幂等可重跑。

SET @ddl := (SELECT IF(
  EXISTS(SELECT 1 FROM information_schema.COLUMNS
         WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='NbrMaster' AND COLUMN_NAME='source_system'),
  'SELECT 1',
  'ALTER TABLE NbrMaster ADD COLUMN source_system VARCHAR(50) NULL DEFAULT NULL COMMENT ''单据来源：AIDOP_LEGACY=本库历史；空/其它由入站或业务写入'' AFTER Remark'));
PREPARE s FROM @ddl; EXECUTE s; DEALLOCATE PREPARE s;

UPDATE NbrMaster
SET source_system = 'AIDOP_LEGACY'
WHERE Type = 'SM'
  AND IFNULL(source_system, '') IN ('', 'AIDOP');

UPDATE mdp_entity
SET status = 0, update_time = NOW(),
    remark = CONCAT(IFNULL(remark, ''), ' | WP9-S5 disabled ', DATE_FORMAT(NOW(), '%Y-%m-%d'))
WHERE entity_code = 'S5_PRODUCTION_ISSUE_MASTER' AND status <> 0;

UPDATE mdp_entity
SET status = 1, update_time = NOW(),
    remark = CONCAT(IFNULL(remark, ''), ' | WP9-S5 enabled ', DATE_FORMAT(NOW(), '%Y-%m-%d'))
WHERE entity_code = 'S5_PRODUCTION_ISSUE_MASTER_SQLSERVER' AND status <> 1;
