-- 将图片生成历史迁移为用户级生图记录，并删除不再使用的模板结构。
CREATE TEMP TABLE legacy_product_image_reference_media ON COMMIT DROP AS
SELECT DISTINCT media_asset_id
FROM product_image_references;

UPDATE generation_tasks
SET input_data = (input_data - 'product_image_template_id') || jsonb_build_object(
    'product_image', true,
    'display_prompt', COALESCE(input_data->>'display_prompt', input_data->>'prompt', '')
)
WHERE input_data->>'product_image_template_id' IS NOT NULL;

DROP TABLE product_image_references;
DROP TABLE product_image_templates;

DELETE FROM channel_asset_cache
WHERE media_asset_id IN (SELECT media_asset_id FROM legacy_product_image_reference_media);

DELETE FROM media_assets
WHERE id IN (SELECT media_asset_id FROM legacy_product_image_reference_media);
