#!/bin/bash

# Script to fix TypeScript route files
echo "Fixing TypeScript route files..."

# Function to fix a TypeScript route file
fix_route() {
    local file=$1
    echo "Fixing: $file"
    
    # Remove duplicate Router imports
    sed -i '' '/^import { Router, Request, Response, NextFunction } from '\''express'\'';$/d' "$file"
    
    # Ensure proper Express types import at the beginning
    if ! grep -q "import.*Request.*Response.*from 'express'" "$file"; then
        # Add the import at the beginning if not present
        sed -i '' '1i\
import { Router, Request, Response, NextFunction } from '\''express'\'';
' "$file"
    fi
    
    # Fix database imports
    sed -i '' "s|from '\.\./\.\./\.\./api/utils/database\.js'|from '../../utils/database.js'|g" "$file"
    sed -i '' "s|from '\.\./\.\./utils/database\.js'|from '../../utils/database.js'|g" "$file"
    
    # Fix response imports
    sed -i '' "s|from '\.\./\.\./\.\./api/utils/response\.js'|from '../../utils/response.js'|g" "$file"
    sed -i '' "s|from '\.\./\.\./utils/response\.js'|from '../../utils/response.js'|g" "$file"
    
    # Fix other util imports
    sed -i '' "s|from '\.\./\.\./\.\./api/|from '../../../api/|g" "$file"
    sed -i '' "s|from '\.\./\.\./|from '../../|g" "$file"
    
    # Add type annotations for common patterns
    sed -i '' 's/router\.\([a-z]*\)(\([^,]*\),\s*async\s*(\([^)]*\))\s*=>/router.\1(\2, async (\3: Request, res: Response) =>/g' "$file"
    
    # Fix callback functions without types
    sed -i '' 's/(\([a-z]*\), \([a-z]*\)) =>/(\1: Request, \2: Response) =>/g' "$file"
    sed -i '' 's/(\([a-z]*\), \([a-z]*\), \([a-z]*\)) =>/(\1: Request, \2: Response, \3: NextFunction) =>/g' "$file"
}

# Fix all TypeScript route files
for dir in src/routes/*; do
    if [ -d "$dir" ]; then
        for file in "$dir"/*.ts; do
            if [ -f "$file" ]; then
                fix_route "$file"
            fi
        done
    fi
done

echo "TypeScript route fixing complete!"