import fs from 'fs'
import path from 'path'
import { execSync } from 'child_process'

// Get all files with the pattern
const files = execSync('grep -rl "const sql = neon(process.env.DATABASE_URL" --include="*.ts" app/ lib/', { encoding: 'utf-8' })
  .trim()
  .split('\n')
  .filter(f => f && !f.includes('node_modules') && !f.includes('scripts/'))

console.log(`Found ${files.length} files to fix`)

for (const file of files) {
  try {
    let content = fs.readFileSync(file, 'utf-8')
    
    // Check if already using shared sql
    if (content.includes('import { sql } from "@/lib/db"') || content.includes("import { sql } from '@/lib/db'")) {
      console.log(`Skipping ${file} - already uses shared sql`)
      continue
    }
    
    // Replace the import and sql declaration
    const newContent = content
      // Remove neon import line
      .replace(/import \{ neon \} from ["']@neondatabase\/serverless["']\n?/g, '')
      // Remove the sql = neon() line
      .replace(/const sql = neon\(process\.env\.DATABASE_URL!\)\n?/g, '')
      // Add the shared sql import after NextResponse import
      .replace(
        /import \{ NextResponse \} from ["']next\/server["']/,
        'import { NextResponse } from "next/server"\nimport { sql } from "@/lib/db"'
      )
    
    // If NextResponse wasn't found, add at the top
    if (!newContent.includes('import { sql } from "@/lib/db"')) {
      const lines = newContent.split('\n')
      lines.splice(1, 0, 'import { sql } from "@/lib/db"')
      fs.writeFileSync(file, lines.join('\n'))
    } else {
      fs.writeFileSync(file, newContent)
    }
    
    console.log(`Fixed: ${file}`)
  } catch (err) {
    console.error(`Error fixing ${file}:`, err.message)
  }
}

console.log('Done!')
