-- Update AI Draft button label in existing module configs
UPDATE modules
SET config = jsonb_set(
  config::jsonb,
  '{body}',
  (
    SELECT jsonb_agg(
      CASE
        WHEN (elem->>'id') = 'aiDraftActions' AND (elem->>'type') = 'html' THEN
          jsonb_set(
            elem,
            '{html}',
            to_jsonb(replace(elem->>'html', 'Generate with EdenAI', 'Generate with AI'))
          )
        ELSE elem
      END
    )
    FROM jsonb_array_elements((config::jsonb)->'body') AS elem
  )
)
WHERE jsonb_typeof((config::jsonb)->'body') = 'array'
  AND EXISTS (
    SELECT 1
    FROM jsonb_array_elements((config::jsonb)->'body') AS elem
    WHERE (elem->>'id') = 'aiDraftActions'
      AND (elem->>'type') = 'html'
      AND (elem->>'html') LIKE '%Generate with EdenAI%'
  );
