#!/bin/bash
# Easypanel Deployment Script for Deal Plus Tech Astro
# Usage: ./deploy-easypanel.sh [api-token]

set -e

EASYPANEL_URL="http://110.164.146.46:3000"
APP_NAME="dealplustech-astro"
PROJECT_NAME="dealplustech"
DOCKER_IMAGE="dealplustech-astro:latest"
PORT=4321
API_TOKEN="${1:-$EASYPANEL_API_TOKEN}"

echo "============================================================"
echo "🚀 Deploying to Easypanel"
echo "============================================================"

# Check if API token is provided
if [ -z "$API_TOKEN" ]; then
    echo "⚠️  No API token provided"
    echo ""
    echo "📋 Manual Deployment Steps:"
    echo "1. Open Easypanel: $EASYPANEL_URL"
    echo "2. Create/Select project: $PROJECT_NAME"
    echo "3. Click 'New Service' → 'Docker Image'"
    echo "4. Enter image: $DOCKER_IMAGE"
    echo "5. Set port: $PORT"
    echo "6. Click 'Deploy'"
    echo ""
    echo "💡 To enable automated deployment:"
    echo "   1. Get API token from Easypanel (Settings → API)"
    echo "   2. Run: export EASYPANEL_API_TOKEN='your-token'"
    echo "   3. Run this script again: ./deploy-easypanel.sh"
    exit 0
fi

# Build Docker image
echo ""
echo "🐳 Building Docker image..."
cd dealplustech-astro
docker build -t $DOCKER_IMAGE . || {
    echo "❌ Docker build failed"
    exit 1
}
echo "✅ Docker image built: $DOCKER_IMAGE"

# Deploy via API
echo ""
echo "🚀 Deploying to Easypanel via API..."

# Create deployment payload
cat > /tmp/deploy.json << EOF
{
  "projectName": "$PROJECT_NAME",
  "name": "$APP_NAME",
  "type": "docker",
  "docker": {
    "image": "$DOCKER_IMAGE",
    "port": $PORT
  },
  "env": {
    "NODE_ENV": "production",
    "PORT": "$PORT",
    "HOST": "0.0.0.0"
  }
}
EOF

# Make API call
RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "$EASYPANEL_URL/api/trpc/services.app.create" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $API_TOKEN" \
  -d @/tmp/deploy.json \
  --insecure)

HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
BODY=$(echo "$RESPONSE" | head -n-1)

if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "201" ]; then
    echo "✅ Service created successfully"
    echo "$BODY" | python3 -m json.tool 2>/dev/null || echo "$BODY"
    
    # Trigger deployment
    echo ""
    echo "🔄 Triggering deployment..."
    # Would need service ID from previous response
    
    echo ""
    echo "============================================================"
    echo "🎉 DEPLOYMENT COMPLETE!"
    echo "============================================================"
    echo ""
    echo "📍 Service: $APP_NAME"
    echo "🔗 Dashboard: $EASYPANEL_URL"
    echo ""
    echo "💡 Check deployment status in Easypanel dashboard"
else
    echo "❌ Deployment failed (HTTP $HTTP_CODE)"
    echo "$BODY"
    exit 1
fi
