namespace Admin.NET.Plugin.AiDOP.DataPlatform;
///
/// 数据中台 stg → std transform 层的 JSON 取值 SQL 表达式生成器(跨源类型兼容)。
///
/// 背景:SQL Server 源经 MdpDbPullExecutor 的 System.Text.Json 序列化后,raw_data JSON 与 MySQL 源不一致:
/// datetime → ISO-8601 2026-07-29T00:00:00(T 分隔);bit → JSON boolean true/false;
/// JSON null → JSON_UNQUOTE 后为字符串 'null'。MySQL STRICT 模式下裸 CAST/STR_TO_DATE 会 500。
///
/// 本类只生成 MySQL transform SQL 表达式字符串,供调用方内插进 INSERT...SELECT;
/// 不改 raw_data、不改 MdpDbPullExecutor/MdpStagingWriter/MdpSourceScopeFactory 核心、不改已运行 entity 的入站行为。
/// 属业务转换辅助,非核心 MDP 修改。字段名 field 为编译期常量,非用户输入,无注入风险。
///
internal static class MdpJsonSql
{
/// 裸取值:JSON_UNQUOTE(JSON_EXTRACT(alias.raw_data,'$.field'))。
private static string Ext(string alias, string field) =>
$"JSON_UNQUOTE(JSON_EXTRACT({alias}.raw_data,'$.{field}'))";
/// 可空字符串:把 JSON null 的 'null' 字符串归一为 SQL NULL。
public static string Str(string alias, string field) =>
$"NULLIF({Ext(alias, field)},'null')";
/// 秒级 datetime:兼容空格/ISO-T/带毫秒,NULL/空/'null' → NULL。
public static string DateTimeSec(string alias, string field) =>
$"STR_TO_DATE(REPLACE(LEFT(NULLIF(NULLIF({Ext(alias, field)},'null'),''),19),'T',' '),'%Y-%m-%d %H:%i:%s')";
/// 可空 DECIMAL:'null'/空 → NULL,避免 CAST('null' AS DECIMAL) STRICT 500。
public static string Dec(string alias, string field, int p, int s) =>
$"CAST(NULLIF(NULLIF({Ext(alias, field)},'null'),'') AS DECIMAL({p},{s}))";
/// 可空整数:'null'/空 → NULL。
public static string Int(string alias, string field) =>
$"CAST(NULLIF(NULLIF({Ext(alias, field)},'null'),'') AS SIGNED)";
/// 布尔判真:兼容 1/0 与 SQL Server bit 序列化的 true/false。
public static string BoolTrue(string alias, string field) =>
$"LOWER({Ext(alias, field)}) IN ('1','true')";
/// 原样取值(不做 'null' 归一):仅用于确知非空/仅展示的场景。
public static string Raw(string alias, string field) => Ext(alias, field);
}