import { useDB, schema } from '../../db'
import { sql } from 'drizzle-orm'

export default defineEventHandler(async (event) => {
  const db = useDB()

  const count = await db
    .select({ count: sql<number>`count(*)` })
    .from(schema.cards)
    .get()
  const randomOffset = Math.floor(Math.random() * count.count)
  const randomCard = await db.select().from(schema.cards).limit(1).offset(randomOffset).get()

  return randomCard
})
