INSERT INTO entity_category_links (
    business_id,
    entity_type,
    entity_id,
    category_id,
    link_role,
    payload_jsonb,
    source_mode,
    created_by_login_id
)
SELECT DISTINCT
    c.business_id,
    'cliente',
    c.id_cliente::bigint,
    cats.category_id,
    'ASSIGNMENT',
    '{}'::jsonb,
    'LEGACY_MAPPED',
    0
FROM clientes c
CROSS JOIN LATERAL (
    SELECT DISTINCT value::integer AS category_id
    FROM jsonb_array_elements_text(
        CASE
            WHEN jsonb_typeof(c.categorias) = 'array' THEN c.categorias
            ELSE '[]'::jsonb
        END
    ) AS src(value)
    WHERE value ~ '^-?[0-9]+$'
      AND value::integer > 0
) AS cats
JOIN categorias_combinables_v2 cc
  ON cc.business_id = c.business_id
 AND cc.category_id = cats.category_id
 AND cc.soft_delete IS NOT TRUE
WHERE COALESCE(c.soft_delete, FALSE) = FALSE
ON CONFLICT DO NOTHING;

INSERT INTO entity_category_links (
    business_id,
    entity_type,
    entity_id,
    category_id,
    link_role,
    payload_jsonb,
    source_mode,
    created_by_login_id
)
SELECT DISTINCT
    k.business_id,
    'conocimiento',
    k.id::bigint,
    cats.category_id,
    'ASSIGNMENT',
    '{}'::jsonb,
    'LEGACY_MAPPED',
    0
FROM conocimientos_empleado_digital k
CROSS JOIN LATERAL (
    SELECT DISTINCT value::integer AS category_id
    FROM jsonb_array_elements_text(
        CASE
            WHEN jsonb_typeof(k.categorias) = 'array' THEN k.categorias
            ELSE '[]'::jsonb
        END
    ) AS src(value)
    WHERE value ~ '^-?[0-9]+$'
      AND value::integer > 0
) AS cats
JOIN categorias_combinables_v2 cc
  ON cc.business_id = k.business_id
 AND cc.category_id = cats.category_id
 AND cc.soft_delete IS NOT TRUE
WHERE COALESCE(k.soft_delete, FALSE) = FALSE
ON CONFLICT DO NOTHING;
