#!/bin/bash
# Script to add getErrorMessage import to files that use it

cd /Users/velikho/Desktop/WORKING/Base/services/iam-service/src

# Find all files that use getErrorMessage but don't have the import
for file in $(find . \( -name "*.controller.ts" -o -name "*.middleware.ts" -o -name "*.service.ts" \) -not -path "*/__tests__/*" -not -name "*.test.ts" -exec grep -l "getErrorMessage" {} \;); do
  # Check if import already exists
  if ! grep -q "getErrorMessage.*from.*error-utils" "$file"; then
    # Calculate relative path to error-utils
    depth=$(echo "$file" | grep -o "/" | wc -l)
    if [ $depth -eq 2 ]; then
      # File is in src/modules/xxx/
      relative_path="../utils/error-utils"
    elif [ $depth -eq 3 ]; then
      # File is in src/modules/xxx/yyy/
      relative_path="../../utils/error-utils"
    elif [ $depth -eq 4 ]; then
      # File is in src/modules/xxx/yyy/zzz/
      relative_path="../../../utils/error-utils"
    else
      # Default to ../../utils/error-utils
      relative_path="../../utils/error-utils"
    fi
    
    # Add import after the last import statement
    awk -v path="$relative_path" '
      /^import/ { last_import=NR }
      { lines[NR]=$0 }
      END {
        for(i=1; i<=NR; i++) {
          print lines[i]
          if(i==last_import) {
            print "import { getErrorMessage } from \"" path "\";"
          }
        }
      }
    ' "$file" > "$file.tmp" && mv "$file.tmp" "$file"
    
    echo "Added import to $file"
  fi
done
