import { PrismaClient } from '@prisma/client'

const globalForPrisma = globalThis as unknown as {
  prisma: PrismaClient | undefined
}

const getDatabaseUrl = () => {
  if (process.env.DATABASE_URL) return process.env.DATABASE_URL
  
  const user = process.env.DB_USER || 'root'
  const pass = process.env.DB_PASSWORD || ''
  const host = process.env.DB_HOST || '127.0.0.1'
  const port = process.env.DB_PORT || '3306'
  const name = process.env.DB_NAME || 'amanenime_topup'
  
  return `mysql://${user}:${pass}@${host}:${port}/${name}`
}

export const prisma =
  globalForPrisma.prisma ??
  new PrismaClient({
    datasources: {
      db: {
        url: getDatabaseUrl(),
      },
    },
    log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
  })

if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma

export default prisma
