#!/bin/bash
set -e

DB_CONTAINER_NAME="aurora_ci_test_db"
DB_PORT="5433"
DB_USER="postgres"
DB_PASS="postgres"
DB_NAME="aurora_test"

echo "🚀 Starting CI Simulation..."

# Cleanup previous run if exists
if docker ps -a --format '{{.Names}}' | grep -q "^${DB_CONTAINER_NAME}$"; then
    echo "🧹 Cleaning up old container..."
    docker rm -f $DB_CONTAINER_NAME
fi

# 1. Start Postgres Service
echo "🐳 Starting temporary PostgreSQL container on port $DB_PORT..."
docker run -d \
    --name $DB_CONTAINER_NAME \
    -e POSTGRES_USER=$DB_USER \
    -e POSTGRES_PASSWORD=$DB_PASS \
    -e POSTGRES_DB=$DB_NAME \
    -p $DB_PORT:5432 \
    postgres:17-alpine

echo "⏳ Waiting for database to be ready..."
# Wait for healthy
for i in {1..30}; do
    if docker exec $DB_CONTAINER_NAME pg_isready -U $DB_USER > /dev/null 2>&1; then
        echo "✅ Database is ready!"
        break
    fi
    echo "   ...waiting ($i/30)"
    sleep 1
done

# Define connection string
export DATABASE_URL="postgresql://$DB_USER:$DB_PASS@127.0.0.1:$DB_PORT/$DB_NAME"

# 2. Create Config File (Match deploy.yml)
echo "📝 Creating shared/config/config.json..."
mkdir -p shared/config
cat <<EOF > shared/config/config.json
{
    "leveling": { "base": 100, "exponent": 2.5, "chat": { "cooldownMs": 60000, "minXp": 15, "maxXp": 25 } },
    "economy": {
        "daily": { "amount": "100", "streakBonus": "10", "weeklyBonus": "50", "cooldownMs": 86400000 },
        "transfers": { "allowSelfTransfer": false, "minAmount": "1" },
        "exam": { "multMin": 0.05, "multMax": 0.03 }
    },
    "inventory": { "maxStackSize": "99", "maxSlots": 50 },
    "commands": {},
    "lootdrop": {
        "activityWindowMs": 120000, "minMessages": 1, "spawnChance": 1, "cooldownMs": 3000,
        "reward": { "min": 40, "max": 150, "currency": "Astral Units" }
    },
    "studentRole": "123", "visitorRole": "456", "colorRoles": [],
    "moderation": {
        "prune": { "maxAmount": 100, "confirmThreshold": 50, "batchSize": 100, "batchDelayMs": 1000 },
        "cases": { "dmOnWarn": false }
    },
    "trivia": {
        "entryFee": "50", "rewardMultiplier": 1.5, "timeoutSeconds": 30, "cooldownMs": 60000,
        "categories": [], "difficulty": "random"
    },
    "system": {}
}
EOF

# 3. Setup Database Schema
echo "📜 Pushing schema to test database..."
bun run db:push:local

# 4. Export Test Env Vars
export DISCORD_BOT_TOKEN="test_token"
export DISCORD_CLIENT_ID="123456789"
export DISCORD_GUILD_ID="123456789"
export ADMIN_TOKEN="admin_token_123"
export LOG_LEVEL="error"

# 5. Run Tests
echo "🧪 Running Tests..."
if [ -n "$1" ]; then
    echo "Running specific test: $1"
    if bun test "$1"; then
        echo "✅ Specific Test Passed!"
        EXIT_CODE=0
    else
        echo "❌ Specific Test Failed!"
        EXIT_CODE=1
    fi
else
    if bash shared/scripts/test-sequential.sh --integration; then
        echo "✅ CI Simulation Passed!"
        EXIT_CODE=0
    else
        echo "❌ CI Simulation Failed!"
        EXIT_CODE=1
    fi
fi

# 6. Cleanup
echo "🧹 Cleaning up container..."
docker rm -f $DB_CONTAINER_NAME

exit $EXIT_CODE
