import { prisma } from "@codeflash-ai/common"
import * as Sentry from "@sentry/nextjs"

interface PrismaQueryEvent {
  timestamp: Date
  query: string
  params: string
  duration: number
  target: string
}

interface PrismaLogEvent {
  timestamp: Date
  message: string
  target: string
}

interface PrismaClientWithEvents {
  $on(event: "query", listener: (e: PrismaQueryEvent) => void): void
  $on(event: "warn" | "error", listener: (e: PrismaLogEvent) => void): void
}

const isProduction = process.env.NODE_ENV === "production"
const SLOW_QUERY_THRESHOLD_MS = 500

// Log slow queries in development
if (!isProduction) {
  ;(prisma as unknown as PrismaClientWithEvents).$on("query", (e: PrismaQueryEvent) => {
    if (e.duration > SLOW_QUERY_THRESHOLD_MS) {
      console.warn(`[Prisma] Slow query (${e.duration}ms): ${e.query}`)
    }
  })
}

// Forward Prisma warnings and errors to Sentry
;(prisma as unknown as PrismaClientWithEvents).$on("warn", (e: PrismaLogEvent) => {
  console.warn("[Prisma] Warning:", e.message)
})
;(prisma as unknown as PrismaClientWithEvents).$on("error", (e: PrismaLogEvent) => {
  console.error("[Prisma] Error:", e.message)
  Sentry.captureException(new Error(`Prisma error: ${e.message}`))
})

export { prisma }
