#!/bin/bash
# Script to refactor Prisma Client instances to use singleton
# Usage: ./scripts/refactor-prisma.sh

echo "Refactoring Prisma Client instances..."

# Find all TypeScript files with PrismaClient
find src -name "*.ts" -type f | while read file; do
  # Skip if already using singleton
  if grep -q "from '@/shared/database/prisma'" "$file"; then
    continue
  fi
  
  # Check if file has "new PrismaClient()"
  if grep -q "new PrismaClient()" "$file"; then
    echo "Processing: $file"
    
    # Create backup
    cp "$file" "$file.bak"
    
    # Replace import
    sed -i "s/import { PrismaClient } from '@prisma\/client';/import prisma from '@\/shared\/database\/prisma';/g" "$file"
    
    # Remove const prisma = new PrismaClient();
    sed -i "/const prisma = new PrismaClient();/d" "$file"
    
    # If PrismaClient is still imported but not used, remove the import line
    if ! grep -q "PrismaClient" "$file"; then
      sed -i "/^import.*PrismaClient/d" "$file"
    fi
    
    echo "  ✓ Refactored: $file"
  fi
done

echo "Refactoring complete!"
echo "Note: Review changes and remove .bak files after verification"

