#!/usr/bin/env bash
# Pack a pre-built Next.js app for cPanel.
# Includes .next (built here). Excludes Mac node_modules — run npm ci on the server once.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
OUT="${1:-$ROOT/../community-cpanel-built.zip}"
cd "$ROOT"

if [[ ! -d .next ]]; then
  echo "Missing .next — run: npm run build" >&2
  exit 1
fi
if [[ ! -f prisma/dev.db ]]; then
  echo "Missing prisma/dev.db — run: npm run db:seed" >&2
  exit 1
fi

# Env for production domain (edit AUTH_SECRET on server if you want)
cat > .env.production.deploy <<'EOF'
DATABASE_URL="file:./dev.db"
AUTH_SECRET="elbeegems-community-preview-change-me"
NEXT_PUBLIC_APP_URL="https://community.elbeegems.com"
NODE_ENV="production"
EOF

rm -f "$OUT"
zip -r "$OUT" . \
  -x "node_modules/*" \
  -x ".cpanel-stage/*" \
  -x ".git/*" \
  -x "*.tsbuildinfo" \
  -x ".env" \
  -x ".DS_Store" \
  -x "*/.DS_Store" \
  -x ".next/cache/*"

# Rename deploy env into the zip as .env
TMP=$(mktemp -d)
unzip -q "$OUT" -d "$TMP"
cp .env.production.deploy "$TMP/.env"
rm -f "$OUT"
(cd "$TMP" && zip -qr "$OUT" .)
rm -rf "$TMP" .env.production.deploy

echo "Wrote $OUT ($(du -h "$OUT" | awk '{print $1}'))"
echo ""
echo "On cPanel after extract (one-time):"
echo "  npm ci --omit=dev"
echo "  npx prisma generate"
echo "  Restart the Node app"
echo "Startup file: server.js"
echo ""
echo "No 'npm run build' needed on the server."
