UPDATE qipai_advertisements a
INNER JOIN qipai_media_assets current_asset
  ON current_asset.tenant_id = a.tenant_id AND current_asset.id = a.image_asset_id
INNER JOIN (
  SELECT tenant_id, checksum_sha256, MIN(id) AS retained_id
  FROM qipai_media_assets
  GROUP BY tenant_id, checksum_sha256
) duplicate_group
  ON duplicate_group.tenant_id = current_asset.tenant_id
  AND duplicate_group.checksum_sha256 = current_asset.checksum_sha256
SET a.image_asset_id = duplicate_group.retained_id
WHERE a.image_asset_id <> duplicate_group.retained_id;

DELETE duplicate_asset
FROM qipai_media_assets duplicate_asset
INNER JOIN (
  SELECT tenant_id, checksum_sha256, MIN(id) AS retained_id
  FROM qipai_media_assets
  GROUP BY tenant_id, checksum_sha256
) duplicate_group
  ON duplicate_group.tenant_id = duplicate_asset.tenant_id
  AND duplicate_group.checksum_sha256 = duplicate_asset.checksum_sha256
WHERE duplicate_asset.id <> duplicate_group.retained_id;

ALTER TABLE qipai_media_assets
  DROP INDEX uq_qipai_media_scope_checksum,
  DROP COLUMN scope_store_id,
  ADD UNIQUE KEY uq_qipai_media_tenant_checksum (tenant_id, checksum_sha256);

DELETE FROM qipai_schema_migrations
WHERE version = '2026081002';
