-- ============================================
-- 诊断脚本：定位 delivery 端地址空白问题
-- 请复制全部内容执行，把结果截图发给我
-- ============================================

-- 诊断1：确认 delivery_build_order_json 当前版本
SELECT 
    proname,
    CASE 
        WHEN prosrc LIKE '%NULLIF(p_raw -> ''address_snapshot_json'', ''{}''::jsonb)%' THEN 'FIXED (含 NULLIF 排除空对象)'
        WHEN prosrc LIKE '%p_raw -> ''address_snapshot''%' THEN 'HAS_FALLBACK 但缺少 NULLIF'
        ELSE 'NO_FALLBACK (只有 address_snapshot_json)'
    END AS address_fallback_status,
    CASE 
        WHEN prosrc LIKE '%|| jsonb_build_object%' THEN 'SPLIT (小块拼接)'
        ELSE 'SINGLE_BLOCK (单个大块)'
    END AS function_structure
FROM pg_proc 
WHERE proname = 'delivery_build_order_json';


-- 诊断2：查看 ec_care_tasks 最近5条订单的地址数据状态
SELECT 
    id,
    task_no,
    elder_name,
    assigned_to,
    COALESCE(address_snapshot_json::TEXT, 'NULL') AS addr_json_raw,
    COALESCE(address_snapshot::TEXT, 'NULL') AS addr_snap_raw,
    CASE 
        WHEN address_snapshot_json IS NULL THEN 'json_null'
        WHEN address_snapshot_json = '{}'::jsonb THEN 'json_empty'
        WHEN address_snapshot_json = 'null'::jsonb THEN 'json_literal_null'
        ELSE 'json_has_data'
    END AS json_status,
    CASE 
        WHEN address_snapshot IS NULL THEN 'snap_null'
        WHEN address_snapshot = '{}'::jsonb THEN 'snap_empty'
        WHEN address_snapshot = 'null'::jsonb THEN 'snap_literal_null'
        ELSE 'snap_has_data'
    END AS snap_status
FROM public.ec_care_tasks
ORDER BY created_at DESC
LIMIT 5;


-- 诊断3：直接测试 delivery_build_order_json 对最近一条 care 订单的输出
-- 如果返回的 address 为空字符串，说明函数内部有问题
SELECT 
    t.id,
    t.task_no,
    delivery_build_order_json(
        to_jsonb(t),
        '[]'::jsonb, '[]'::jsonb, '[]'::jsonb, NULL, 'care'
    ) ->> 'address' AS test_address,
    delivery_build_order_json(
        to_jsonb(t),
        '[]'::jsonb, '[]'::jsonb, '[]'::jsonb, NULL, 'care'
    ) ->> 'elderGender' AS test_gender,
    delivery_build_order_json(
        to_jsonb(t),
        '[]'::jsonb, '[]'::jsonb, '[]'::jsonb, NULL, 'care'
    ) ->> 'elderAge' AS test_age
FROM public.ec_care_tasks t
ORDER BY t.created_at DESC
LIMIT 1;
