#!/bin/bash
set -e

CREDENTIALS_FILE="$HOME/.easypanel/credentials"
if [ -f "$CREDENTIALS_FILE" ]; then
  export $(grep -v '^#' "$CREDENTIALS_FILE" | xargs) 2>/dev/null || true
fi

EASYPANEL_HOST="110.164.146.46"
EASYPANEL_URL="http://${EASYPANEL_HOST}:3000"
GITEA_REPO_URL="https://git.moreminimore.com/kunthawat/dealplustech.git"
PROJECT_NAME="customerwebsite"
GITEA_BRANCH="main"
TIMESTAMP=$(date +%s)
APP_NAME="dealplustech-${TIMESTAMP}"

RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}ℹ️  $1${NC}"; }
log_success() { echo -e "${GREEN}✅ $1${NC}"; }
log_error() { echo -e "${RED}❌ $1${NC}"; }

[ -z "$EASYPANEL_API_TOKEN" ] && { log_error "Token not set"; exit 1; }

echo "========================================"
echo "🚀 Deploying $APP_NAME"
echo "========================================"
echo ""

# Step 1
log_info "Step 1/5: Creating service..."
result=$(curl -s -X POST "${EASYPANEL_URL}/api/trpc/services.app.createService" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $EASYPANEL_API_TOKEN" \
  -d "{\"json\":{\"projectName\":\"$PROJECT_NAME\",\"domains\":[{\"host\":\"\$(EASYPANEL_DOMAIN)\"}],\"serviceName\":\"$APP_NAME\"}}" \
  --insecure)

if echo "$result" | grep -q '"error"'; then
  log_error "Failed: $result"
  exit 1
fi
log_success "✅ Service created: $APP_NAME"

# Step 2
log_info "Step 2/5: Configuring Git..."
log_info "Repository: $GITEA_REPO_URL"
result=$(curl -s -X POST "${EASYPANEL_URL}/api/trpc/services.app.updateSourceGit" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $EASYPANEL_API_TOKEN" \
  -d "{\"json\":{\"projectName\":\"$PROJECT_NAME\",\"serviceName\":\"$APP_NAME\",\"repo\":\"$GITEA_REPO_URL\",\"ref\":\"$GITEA_BRANCH\",\"path\":\"/\"}}" \
  --insecure)

if echo "$result" | grep -q '"error"'; then
  log_error "Failed: $result"
  exit 1
fi
log_success "✅ Git configured"

# Step 3
log_info "Step 3/5: Setting build type..."
result=$(curl -s -X POST "${EASYPANEL_URL}/api/trpc/services.app.updateBuild" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $EASYPANEL_API_TOKEN" \
  -d "{\"json\":{\"projectName\":\"$PROJECT_NAME\",\"serviceName\":\"$APP_NAME\",\"build\":{\"type\":\"nixpacks\"}}}" \
  --insecure)
log_success "✅ Build type set (nixpacks)"

# Step 4
log_info "Step 4/5: Getting domain..."
result=$(curl -s "${EASYPANEL_URL}/api/trpc/domains.getPrimaryDomain?input=%7B%22json%22%3A%7B%22projectName%22%3A%22$PROJECT_NAME%22%2C%22serviceName%22%3A%22$APP_NAME%22%7D%7D" \
  -H "Authorization: Bearer $EASYPANEL_API_TOKEN" --insecure)
domain=$(echo "$result" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('result',{}).get('data',{}).get('domain',{}).get('host','pending'))" 2>/dev/null || echo "pending")
log_success "✅ Domain: $domain"

# Step 5
log_info "Step 5/5: Waiting for deployment..."
for i in 1 2 3 4 5 6 7 8 9 10; do
  sleep 10
  result=$(curl -s "${EASYPANEL_URL}/api/trpc/services.app.inspectService?input=%7B%22json%22%3A%7B%22projectName%22%3A%22$PROJECT_NAME%22%2C%22serviceName%22%3A%22$APP_NAME%22%7D%7D" \
    -H "Authorization: Bearer $EASYPANEL_API_TOKEN" --insecure)
  status=$(echo "$result" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('result',{}).get('data',{}).get('status','building'))" 2>/dev/null || echo "building")
  log_info "  Status: $status (attempt $i/10)"
  [ "$status" = "running" ] || [ "$status" = "ready" ] && break
done

log_success "✅ Deployment complete!"
log_info ""
log_info "Service: $APP_NAME"
log_info "URL: http://$domain"
log_info ""
log_info "To redeploy: ./deploy.sh redeploy $APP_NAME"
