import mongoose from 'mongoose'
import { connectDB } from '../utils/mongoose.js'

export default defineEventHandler(async () => {
  try {
    await connectDB()
    const dbState = mongoose.connection.readyState
    // readyState: 0 = disconnected, 1 = connected, 2 = connecting, 3 = disconnecting
    if (dbState !== 1) {
      throw new Error('Database not connected')
    }
    return { status: 'ok', db: 'connected' }
  } catch {
    throw createError({
      statusCode: 503,
      data: { status: 'error', db: 'disconnected' },
    })
  }
})
