-- ============================================================================
-- Migration 001: tbl_cskh_msg_v2
-- CHỈ THÊM BẢNG MỚI, KHÔNG đụng tới tbl_cskh_msg cũ.
-- An toàn chạy trên DB đang chạy sản xuất (dbqqopcm_nksgcskh).
-- Tương thích MariaDB 10.11.
-- ============================================================================

CREATE TABLE IF NOT EXISTS `tbl_cskh_msg_v2` (
  `id`            BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `template_id`   VARCHAR(10)  NOT NULL,
  `msg_id`        VARCHAR(30)  DEFAULT NULL,
  `branch_index`  SMALLINT     NOT NULL COMMENT 'index chi nhánh theo config/branches.php',
  `branch_code`   VARCHAR(20)  NOT NULL COMMENT 'sttpk, vd CN01, CN LUXURY',
  `service_group` VARCHAR(20)  NOT NULL COMMENT 'nksg | wls | sales...',
  `profiles_id`   INT          NOT NULL,
  `ma_dieutri`    INT          DEFAULT NULL,
  `phone`         VARCHAR(20)  NOT NULL,
  `status`        TINYINT      NOT NULL DEFAULT 0 COMMENT '0=success, khác 0 = mã lỗi Zalo trả về',
  `msg`           VARCHAR(150) DEFAULT NULL,
  `data_json`     JSON         DEFAULT NULL,
  `sent_time`     DATETIME     DEFAULT NULL,
  `created_at`    DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_branch_time` (`branch_index`, `created_at`),
  KEY `idx_template_time` (`template_id`, `created_at`),
  KEY `idx_status_time` (`status`, `created_at`),
  KEY `idx_phone` (`phone`),
  KEY `idx_profiles` (`profiles_id`, `ma_dieutri`),
  KEY `idx_service_group_time` (`service_group`, `created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='Lịch sử tin nhắn ZNS - bảng mới, chạy song song với tbl_cskh_msg trong giai đoạn chuyển đổi';

-- Ghi chú migrate dữ liệu cũ (chạy TAY, sau khi xác nhận cấu trúc ổn định,
-- KHÔNG chạy tự động để tránh trùng lặp nếu chạy migration nhiều lần):
--
-- INSERT INTO tbl_cskh_msg_v2
--   (template_id, msg_id, branch_index, branch_code, service_group,
--    profiles_id, ma_dieutri, phone, status, msg, data_json, sent_time, created_at)
-- SELECT
--   template_id, msg_id,
--   0 AS branch_index,          -- cần map branchDC -> branch_index bằng script PHP
--   branchDC AS branch_code,
--   'nksg' AS service_group,    -- cần xác định đúng theo dữ liệu thật
--   ProfilesID, MaDieutri, phone,
--   CAST(error AS SIGNED) AS status,
--   msg,
--   JSON_VALID(data_string) THEN CAST(data_string AS JSON) ELSE NULL END,
--   NULLIF(sent_time,'') , createdDT
-- FROM tbl_cskh_msg;
--
-- (Việc map branchDC -> branch_index chính xác cần chạy qua
--  Cskh\Core\BranchRegistry::findIndexBySttPK() trong PHP, không nên
--  làm thuần SQL vì mapping không tuyến tính — xem config/branches.php)
