-- Update the translations for product options that are added to PRODUCT and their attribute choices. i.e. options[1].attributeChoice.allowedValues[0].label
CREATE TEMP TABLE temp_product_attr_choice_translation AS
SELECT id AS translation_id, entity_id AS product_id, entity_field AS old_entity_field, (SUBSTRING(entity_field, 'options\[(.+)\].attributeChoice'))::int AS option_index, NULL AS option_id, (SUBSTRING(entity_field, 'allowedValues\[(.+)\].label'))::int AS allowed_value_index, NULL AS allowed_value_id, NULL AS updated_entity_field
FROM "catalog".blc_translation
WHERE (trk_archived IS NULL OR trk_archived='N')
AND (trk_sandbox_archived IS NULL OR trk_sandbox_archived='N')
AND trk_level = 100000
AND entity_type='com.broadleafcommerce.catalog.provider.jpa.domain.product.JpaProduct'
AND entity_field LIKE '%.allowedValues[%'
AND entity_field NOT LIKE '%allowedValues[?(@.id==''%';
UPDATE temp_product_attr_choice_translation
SET option_id = (
SELECT "options"::json -> option_index -> 'id'
FROM "catalog".blc_product product
WHERE (product.trk_archived IS NULL OR product.trk_archived='N')
AND (product.trk_sandbox_archived IS NULL OR product.trk_sandbox_archived='N')
AND product.trk_level = 100000
AND product.context_id=product_id);
UPDATE temp_product_attr_choice_translation
SET allowed_value_id = (
SELECT "options"::json -> option_index -> 'attributeChoice' -> 'allowedValues' -> allowed_value_index -> 'id'
FROM "catalog".blc_product product
WHERE (product.trk_archived IS NULL OR product.trk_archived='N')
AND (product.trk_sandbox_archived IS NULL OR product.trk_sandbox_archived='N')
AND product.trk_level = 100000
AND product.context_id=product_id);
UPDATE temp_product_attr_choice_translation
SET updated_entity_field = REPLACE(old_entity_field, concat('options[', option_index, ']'), concat('options[?(@.id==''', translate(option_id, '"', ''), ''')]'));
UPDATE temp_product_attr_choice_translation
SET updated_entity_field = REPLACE(updated_entity_field, concat('allowedValues[', allowed_value_index, ']'), concat('allowedValues[?(@.id==''', translate(allowed_value_id, '"', ''), ''')]'));
UPDATE "catalog".blc_translation
SET entity_field = temp.updated_entity_field
FROM (SELECT translation_id, updated_entity_field FROM temp_product_attr_choice_translation) AS temp
WHERE id = temp.translation_id;