import fp from 'fastify-plugin';
import mongoose from 'mongoose';
import { diContainer } from '@fastify/awilix';
import { asValue } from 'awilix';
import config from '../config/configuration.js';

export default fp(
  async (fastify) => {
    fastify.log.info('Connecting to MongoDB...');
    await mongoose.connect(config.mongodb.uri);
    fastify.log.info('MongoDB connected');

    // Register mongoose in DI container for other services to use
    diContainer.register({ mongoose: asValue(mongoose) });

    fastify.addHook('onClose', async () => {
      fastify.log.info('Closing MongoDB connection...');
      await mongoose.disconnect();
    });
  },
  { name: 'mongoose-plugin' },
);
