#!/bin/bash
# Script completo per fixare deployment su vt.alfacom.it

echo "🔧 Fix Deployment Server - vt.alfacom.it"
echo "=========================================="

# 1. Fix package.json scripts per usare npx (più robusto)
echo "📝 Step 1: Aggiornamento package.json scripts..."
cat > /tmp/fix_package.json << 'PKGFIX'
{
  "scripts": {
    "dev": "NODE_ENV=development tsx server/index.ts",
    "build": "vite build && esbuild server/index.ts --platform=node --packages=external --bundle --format=esm --outdir=dist",
    "start": "NODE_ENV=production node dist/index.js",
    "check": "tsc",
    "db:push": "drizzle-kit push --force || drizzle-kit push || echo 'DB schema sync skipped'"
  }
}
PKGFIX

# Leggi package.json corrente e aggiorna solo scripts
node -e "
const pkg = JSON.parse(require('fs').readFileSync('./package.json', 'utf8'));
const newScripts = JSON.parse(require('fs').readFileSync('/tmp/fix_package.json', 'utf8')).scripts;
pkg.scripts = newScripts;
require('fs').writeFileSync('./package.json', JSON.stringify(pkg, null, 2));
" 2>/dev/null || {
  echo "⚠️  Node.js update fallito, usa modifica manuale"
  echo "   Aggiorna scripts in package.json con:"
  echo '   "db:push": "drizzle-kit push --force || drizzle-kit push || echo DB schema sync skipped"'
}

# 2. Aggiorna .env con variabili deployment
echo ""
echo "📝 Step 2: Verifica .env..."
if [ ! -f .env ]; then
  echo "❌ File .env non trovato!"
  exit 1
fi

# Aggiungi DOMAIN se non esiste
if ! grep -q "^DOMAIN=" .env; then
  echo "DOMAIN=vt.alfacom.it" >> .env
  echo "✅ Aggiunto DOMAIN=vt.alfacom.it"
fi

# Aggiungi ISSUER_URL se non esiste
if ! grep -q "^ISSUER_URL=" .env; then
  echo "ISSUER_URL=https://replit.com/oidc" >> .env
  echo "✅ Aggiunto ISSUER_URL"
fi

# 3. Verifica deploy.sh usa npm ci --include=dev
echo ""
echo "📝 Step 3: Verifica deploy.sh..."
if grep -q "npm ci --include=dev" deploy/deploy.sh; then
  echo "✅ deploy.sh già configurato correttamente"
else
  sed -i 's/^npm ci$/npm ci --include=dev/' deploy/deploy.sh
  echo "✅ Aggiornato deploy.sh per includere devDependencies"
fi

echo ""
echo "✅ Fix completato!"
echo ""
echo "📋 Riepilogo modifiche:"
echo "  ✓ package.json scripts aggiornati"
echo "  ✓ .env con DOMAIN e ISSUER_URL"
echo "  ✓ deploy.sh usa npm ci --include=dev"
echo ""
echo "🚀 Esegui deployment con:"
echo "   bash deploy/deploy.sh"
