-- 禁用外键检查
SET FOREIGN_KEY_CHECKS = 0;

-- 设置SQL模式以允许零日期
SET SQL_MODE = '';

-- 清空目标表避免主键冲突
TRUNCATE TABLE tg_account;
TRUNCATE TABLE tg_firstname;
TRUNCATE TABLE tg_lastname;
TRUNCATE TABLE tg_group;
TRUNCATE TABLE tg_message;
TRUNCATE TABLE tg_config;
TRUNCATE TABLE tg_script;
TRUNCATE TABLE tg_script_article;
TRUNCATE TABLE tg_script_project;
TRUNCATE TABLE tg_script_task;

-- 迁移TG账号数据，处理无效日期
INSERT INTO tg_account (id, firstname, lastname, phone, password, usageId, isBan, lastOnline, createdAt, updatedAt, status, session, banTime, nextTime, addGroupIds, about, targetId)
SELECT 
    id, 
    firstname, 
    lastname, 
    phone, 
    password, 
    usageId, 
    isBan, 
    CASE WHEN lastOnline = '0000-00-00 00:00:00' THEN NULL ELSE lastOnline END,
    createdAt, 
    updatedAt, 
    status, 
    session, 
    CASE WHEN banTime = '0000-00-00 00:00:00' THEN NULL ELSE banTime END,
    nextTime, 
    addGroupIds, 
    about, 
    targetId
FROM c_tg_account;

-- 迁移名字数据
INSERT INTO tg_firstname SELECT * FROM c_firstname;
INSERT INTO tg_lastname SELECT * FROM c_lastname;

-- 迁移群组数据
INSERT IGNORE INTO tg_group SELECT * FROM c_group;

-- 迁移消息数据
INSERT IGNORE INTO tg_message SELECT * FROM c_message;

-- 迁移配置数据
INSERT IGNORE INTO tg_config SELECT * FROM c_config;

-- 迁移脚本相关数据
INSERT IGNORE INTO tg_script SELECT * FROM c_script;
INSERT IGNORE INTO tg_script_article SELECT * FROM c_script_article;
INSERT IGNORE INTO tg_script_project SELECT * FROM c_script_project;
INSERT IGNORE INTO tg_script_task SELECT * FROM c_script_task;

-- 重新启用外键检查
SET FOREIGN_KEY_CHECKS = 1;

-- 查看迁移结果
SELECT 'tg_account' as table_name, COUNT(*) as count FROM tg_account
UNION ALL
SELECT 'tg_firstname', COUNT(*) FROM tg_firstname
UNION ALL
SELECT 'tg_lastname', COUNT(*) FROM tg_lastname
UNION ALL
SELECT 'tg_group', COUNT(*) FROM tg_group
UNION ALL
SELECT 'tg_message', COUNT(*) FROM tg_message;