-- 为已有存量资产补建资产钱包
-- IoT 卡和设备导入时未创建钱包，需要补建以确保 C 端购买流程正常

-- 为没有钱包的 IoT 卡创建钱包
INSERT INTO tb_asset_wallet (resource_type, resource_id, balance, frozen_balance, currency, status, version, shop_id_tag, created_at, updated_at)
SELECT 'iot_card', c.id, 0, 0, 'CNY', 1, 0, COALESCE(c.shop_id, 0), NOW(), NOW()
FROM tb_iot_card c
WHERE c.deleted_at IS NULL
  AND NOT EXISTS (
    SELECT 1 FROM tb_asset_wallet w
    WHERE w.resource_type = 'iot_card' AND w.resource_id = c.id AND w.deleted_at IS NULL
  );

-- 为没有钱包的设备创建钱包
INSERT INTO tb_asset_wallet (resource_type, resource_id, balance, frozen_balance, currency, status, version, shop_id_tag, created_at, updated_at)
SELECT 'device', d.id, 0, 0, 'CNY', 1, 0, COALESCE(d.shop_id, 0), NOW(), NOW()
FROM tb_device d
WHERE d.deleted_at IS NULL
  AND NOT EXISTS (
    SELECT 1 FROM tb_asset_wallet w
    WHERE w.resource_type = 'device' AND w.resource_id = d.id AND w.deleted_at IS NULL
  );
