import fastifyPlugin from "fastify-plugin"
import mongoose from "mongoose"

export default fastifyPlugin(async (fastify, opts: { uri: string }) => {
  if (!opts.uri) {
    throw new Error(
      "MongoDB URI is not provided. Please set the MONGO_HOST environment variable.",
    )
  }

  try {
    // Connect to MongoDB
    await mongoose.connect(opts.uri)
    const database = mongoose.connection

    database.on(
      "error",
      console.error.bind(console, "MongoDB connection error:"),
    )
    database.once("open", () => {
      fastify.log.info(`MongoDB connected.`)
    })

    fastify.decorate("database", database)
  } catch (error: any) {
    fastify.log.error(`Failed to connect to MongoDB: ${error.message}`)
    throw error // Ensure that Fastify doesn't start if MongoDB connection fails
  }
})
