#!/bin/bash
# Fix npm and Prisma dependency issues
# Run this script when connected to the container to resolve installation problems

set -e

LOG_FILE="/app/logs/npm-fix.log"
echo "[$(date)] Starting npm fix script" | tee -a $LOG_FILE

# Navigate to app directory
cd /app
echo "[$(date)] Working in directory: $(pwd)" | tee -a $LOG_FILE

# Clean up problematic packages
echo "[$(date)] Removing problematic packages..." | tee -a $LOG_FILE
rm -rf node_modules/abbrev 2>/dev/null || true
rm -rf node_modules/bcrypt 2>/dev/null || true
rm -rf node_modules/.prisma 2>/dev/null || true

# Clean up Prisma nested modules
echo "[$(date)] Cleaning up Prisma dependencies..." | tee -a $LOG_FILE
rm -rf node_modules/@prisma/internals/node_modules/@prisma/engines 2>/dev/null || true
rm -rf node_modules/@prisma/internals/node_modules/@prisma/engines-version 2>/dev/null || true
rm -rf node_modules/@prisma/client/node_modules/@prisma/engines-version 2>/dev/null || true

# Clean npm cache
echo "[$(date)] Cleaning npm cache..." | tee -a $LOG_FILE
npm cache clean --force

# Fix nested node_modules issues
echo "[$(date)] Removing nested node_modules..." | tee -a $LOG_FILE
find node_modules -type d -name "node_modules" -not -path "node_modules" -exec rm -rf {} + 2>/dev/null || true

# Install critical packages individually
echo "[$(date)] Installing critical packages individually..." | tee -a $LOG_FILE
npm install abbrev@latest --no-save --no-audit --no-fund | tee -a $LOG_FILE
npm install bcrypt@latest --build-from-source --no-save --no-audit --no-fund | tee -a $LOG_FILE

# Install specific Prisma versions
echo "[$(date)] Installing specific Prisma versions..." | tee -a $LOG_FILE
npm uninstall prisma @prisma/client --no-save | tee -a $LOG_FILE
npm install prisma@5.12.0 @prisma/client@5.12.0 --save-exact --no-audit --no-fund | tee -a $LOG_FILE

# Reinstall all dependencies with safer options
echo "[$(date)] Reinstalling all dependencies..." | tee -a $LOG_FILE
npm install --production --no-optional --legacy-peer-deps | tee -a $LOG_FILE

# Generate Prisma client
echo "[$(date)] Generating Prisma client..." | tee -a $LOG_FILE
npx prisma generate | tee -a $LOG_FILE

# Rebuild Next.js
echo "[$(date)] Building Next.js application..." | tee -a $LOG_FILE
npx next build | tee -a $LOG_FILE

echo "[$(date)] Fix script completed. Check for any errors above." | tee -a $LOG_FILE
echo "[$(date)] You may need to restart the application now: npm start" | tee -a $LOG_FILE

# Print instructions for running the script in the background
cat << "EOF"

To run this script in the background (detached from terminal):
nohup /app/_deploy/fix-npm-issues.sh > /app/logs/npm-fix.log 2>&1 &

To monitor progress:
tail -f /app/logs/npm-fix.log

To restart the application after fixing:
pkill -f "npm start" || true
nohup npm start > /app/logs/app.log 2>&1 &

EOF 