import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'

export async function POST(request: NextRequest) {
  try {
    // Get all services with invalid iconUrl
    const services = await db.service.findMany({
      where: {
        OR: [
          { iconUrl: { contains: '🚗' } },
          { iconUrl: { not: { startsWith: '/' } } },
          { iconUrl: { not: { startsWith: 'http' } } }
        ]
      }
    })

    // Clean up invalid iconUrls
    for (const service of services) {
      if (service.iconUrl && (!service.iconUrl.startsWith('/') && !service.iconUrl.startsWith('http'))) {
        await db.service.update({
          where: { id: service.id },
          data: { iconUrl: null }
        })
        console.log(`Cleaned invalid iconUrl for service: ${service.title}`)
      }
    }

    return NextResponse.json({
      success: true,
      message: `Cleaned ${services.length} services with invalid iconUrls`,
      cleanedServices: services.map(s => ({ id: s.id, title: s.title, iconUrl: s.iconUrl }))
    })
  } catch (error) {
    console.error('Error cleaning database:', error)
    return NextResponse.json(
      { error: 'Failed to clean database' },
      { status: 500 }
    )
  }
}