import fp from 'fastify-plugin';
import type { FastifyInstance } from 'fastify';
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from '../../db/schema/index.js';

declare module 'fastify' {
  interface FastifyInstance {
    db: ReturnType<typeof drizzle<typeof schema>>;
  }
}

export default fp(async function dbPlugin(fastify: FastifyInstance) {
  const client = postgres(fastify.config.DATABASE_URL);
  const db = drizzle(client, { schema });
  fastify.decorate('db', db);

  fastify.addHook('onClose', async () => {
    await client.end();
  });
});
