USE hyapp_wallet;

DROP PROCEDURE IF EXISTS migrate_resource_group_wallet_asset_items;

DELIMITER $$

CREATE PROCEDURE migrate_resource_group_wallet_asset_items()
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'resource_group_items' AND COLUMN_NAME = 'item_type'
  ) THEN
    ALTER TABLE resource_group_items
      ADD COLUMN item_type VARCHAR(32) NOT NULL DEFAULT 'resource' AFTER group_id;
  END IF;

  IF NOT EXISTS (
    SELECT 1 FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'resource_group_items' AND COLUMN_NAME = 'wallet_asset_type'
  ) THEN
    ALTER TABLE resource_group_items
      ADD COLUMN wallet_asset_type VARCHAR(32) NOT NULL DEFAULT '' AFTER resource_id;
  END IF;

  IF NOT EXISTS (
    SELECT 1 FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'resource_group_items' AND COLUMN_NAME = 'wallet_asset_amount'
  ) THEN
    ALTER TABLE resource_group_items
      ADD COLUMN wallet_asset_amount BIGINT NOT NULL DEFAULT 0 AFTER wallet_asset_type;
  END IF;

  IF EXISTS (
    SELECT 1 FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'resource_group_items' AND INDEX_NAME = 'uk_resource_group_items_resource'
  ) THEN
    ALTER TABLE resource_group_items DROP INDEX uk_resource_group_items_resource;
  END IF;

  IF NOT EXISTS (
    SELECT 1 FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'resource_group_items' AND INDEX_NAME = 'uk_resource_group_items_member'
  ) THEN
    ALTER TABLE resource_group_items
      ADD UNIQUE KEY uk_resource_group_items_member (app_code, group_id, item_type, resource_id, wallet_asset_type);
  END IF;
END$$

DELIMITER ;

CALL migrate_resource_group_wallet_asset_items();

DROP PROCEDURE migrate_resource_group_wallet_asset_items;
