#!/bin/bash

# Script to add specific PLA Basic colors to production database

echo "🎨 Adding PLA Basic colors to production database..."

# Get the RDS endpoint from terraform output
DB_HOST=$(cat terraform-outputs.json | grep -A1 "rds_endpoint" | grep "value" | cut -d'"' -f4 | cut -d':' -f1)

if [ -z "$DB_HOST" ]; then
    echo "❌ Could not find RDS endpoint in terraform-outputs.json"
    exit 1
fi

echo "📍 Database host: $DB_HOST"

# Execute the migration
echo "🚀 Running migration..."
aws ssm send-command \
    --document-name "AWS-RunShellScript" \
    --targets "Key=tag:Name,Values=filamenteka-api-instance" \
    --parameters commands="[\"PGPASSWORD=\$DB_PASSWORD psql -h $DB_HOST -U filamenteka -d filamenteka -f /tmp/add_pla_colors.sql\"]" \
    --region eu-central-1 \
    --query "Command.CommandId" \
    --output text > /tmp/command-id.txt

COMMAND_ID=$(cat /tmp/command-id.txt)
echo "⏳ Command ID: $COMMAND_ID"

# Wait for command to complete
echo "⏳ Waiting for migration to complete..."
sleep 5

# Check command status
aws ssm get-command-invocation \
    --command-id "$COMMAND_ID" \
    --instance-id $(aws ec2 describe-instances --filters "Name=tag:Name,Values=filamenteka-api-instance" --query "Reservations[0].Instances[0].InstanceId" --output text --region eu-central-1) \
    --region eu-central-1 \
    --query "Status" \
    --output text

echo "✅ Migration completed!"
echo ""
echo "📝 Summary of changes:"
echo "- Added 30 specific PLA Basic colors"
echo "- Each color has 1 refill AND 1 spool (total quantity: 2)"
echo "- Price set to 3499/3999 RSD"
echo "- Zeroed out ALL other filaments (they won't show in the table)"

# Cleanup
rm -f /tmp/command-id.txt