#!/bin/bash
# Initialize reserves for tokenization system

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configuration
FABRIC_NETWORK="${FABRIC_NETWORK:-fabric-network}"
CACTI_API_URL="${CACTI_API_URL:-http://localhost:4000}"

echo -e "${GREEN}Initializing reserves for tokenization system...${NC}"

# Reserve configurations
declare -A RESERVES=(
    ["RESERVE-EUR-001"]="EUR:1000000.00"
    ["RESERVE-USD-001"]="USD:1000000.00"
    ["RESERVE-GBP-001"]="GBP:1000000.00"
)

# Initialize each reserve
for reserve_id in "${!RESERVES[@]}"; do
    IFS=':' read -r asset_type total_amount <<< "${RESERVES[$reserve_id]}"
    
    echo -e "${YELLOW}Creating reserve: $reserve_id ($asset_type: $total_amount)${NC}"
    
    # Create reserve via Cacti (Fabric chaincode)
    response=$(curl -s -X POST "${CACTI_API_URL}/api/v1/plugins/ledger-connector/fabric/invoke" \
        -H "Content-Type: application/json" \
        -d "{
            \"chaincodeId\": \"reserve-manager\",
            \"functionName\": \"CreateReserve\",
            \"args\": [\"{
                \\\"reserveId\\\": \\\"${reserve_id}\\\",
                \\\"assetType\\\": \\\"${asset_type}\\\",
                \\\"totalAmount\\\": \\\"${total_amount}\\\",
                \\\"attestor\\\": \\\"DBIS\\\",
                \\\"attestationHash\\\": \\\"0x$(openssl rand -hex 32)\\\",
                \\\"proof\\\": \\\"initial\\\"
            }\"]
        }")
    
    if echo "$response" | grep -q "success"; then
        echo -e "${GREEN}✓ Reserve $reserve_id created successfully${NC}"
    else
        echo -e "${RED}✗ Failed to create reserve $reserve_id${NC}"
        echo "Response: $response"
    fi
done

echo -e "${GREEN}Reserve initialization complete!${NC}"
