const fastifyPlugin = require('fastify-plugin');
const { MongoClient } = require('mongodb');

async function dbConnector(fastify, options) {
  const url = process.env.MONGO_URI;
  const dbName = process.env.DATABASE_NAME;
  
  if (!url) {
      throw new Error('MONGO_URI must be defined in your .env file');
  }

  const client = new MongoClient(url);

  try {
    await client.connect();
    fastify.log.info('成功连接到 MongoDB 数据库!');
    
    const db = client.db(dbName);
    
    // 使用 fastify.decorate 将数据库实例和 ObjectId 挂载到 Fastify 实例上
    // 这样在所有路由中都可以通过 fastify.mongo.db 访问
    fastify.decorate('mongo', { db });

  } catch (err) {
    fastify.log.error(err);
    // 如果连接失败，可以选择关闭 fastify 实例或抛出错误
    throw new Error('数据库连接失败');
  }

  // 确保在服务器关闭时断开数据库连接
  fastify.addHook('onClose', async (instance) => {
    await client.close();
    instance.log.info('MongoDB 数据库连接已断开。');
  });
}

// 使用 fastify-plugin 包装，防止 Fastify 对插件进行不必要的封装
module.exports = fastifyPlugin(dbConnector);