-- 修正基础数据导入后的自增序列
-- 用途：避免显式插入 ID 后，后续新增数据仍从旧序列值开始

SELECT setval(
    pg_get_serial_sequence('"tb_permission"', 'id'),
    COALESCE((SELECT MAX(id) FROM tb_permission), 1),
    (SELECT COUNT(*) > 0 FROM tb_permission)
);

SELECT setval(
    pg_get_serial_sequence('"tb_role"', 'id'),
    COALESCE((SELECT MAX(id) FROM tb_role), 1),
    (SELECT COUNT(*) > 0 FROM tb_role)
);

SELECT setval(
    pg_get_serial_sequence('"tb_role_permission"', 'id'),
    COALESCE((SELECT MAX(id) FROM tb_role_permission), 1),
    (SELECT COUNT(*) > 0 FROM tb_role_permission)
);

SELECT setval(
    pg_get_serial_sequence('"tb_carrier"', 'id'),
    COALESCE((SELECT MAX(id) FROM tb_carrier), 1),
    (SELECT COUNT(*) > 0 FROM tb_carrier)
);

SELECT setval(
    pg_get_serial_sequence('"tb_wechat_config"', 'id'),
    COALESCE((SELECT MAX(id) FROM tb_wechat_config), 1),
    (SELECT COUNT(*) > 0 FROM tb_wechat_config)
);

SELECT setval(
    pg_get_serial_sequence('"tb_commission_withdrawal_setting"', 'id'),
    COALESCE((SELECT MAX(id) FROM tb_commission_withdrawal_setting), 1),
    (SELECT COUNT(*) > 0 FROM tb_commission_withdrawal_setting)
);

SELECT setval(
    pg_get_serial_sequence('"tb_polling_config"', 'id'),
    COALESCE((SELECT MAX(id) FROM tb_polling_config), 1),
    (SELECT COUNT(*) > 0 FROM tb_polling_config)
);

SELECT setval(
    pg_get_serial_sequence('"tb_polling_concurrency_config"', 'id'),
    COALESCE((SELECT MAX(id) FROM tb_polling_concurrency_config), 1),
    (SELECT COUNT(*) > 0 FROM tb_polling_concurrency_config)
);

SELECT setval(
    pg_get_serial_sequence('"tb_polling_alert_rule"', 'id'),
    COALESCE((SELECT MAX(id) FROM tb_polling_alert_rule), 1),
    (SELECT COUNT(*) > 0 FROM tb_polling_alert_rule)
);

SELECT setval(
    pg_get_serial_sequence('"tb_data_cleanup_config"', 'id'),
    COALESCE((SELECT MAX(id) FROM tb_data_cleanup_config), 1),
    (SELECT COUNT(*) > 0 FROM tb_data_cleanup_config)
);
