import { Global, Inject, Module, OnApplicationShutdown } from "@nestjs/common";
import { Pool } from "pg";
import { drizzle, NodePgDatabase } from "drizzle-orm/node-postgres";
import { ConfigModule, ConfigService } from "@nestjs/config";
import * as schema from '../../drizzle/schema';

@Global()
@Module({
  imports: [ConfigModule], 
  providers: [
    {
      provide: "DB_POOL",
      useFactory: (configService: ConfigService) => {
        return new Pool({
          connectionString: configService.get<string>('PG_DATABASE_URL')
        });
      },
      inject: [ConfigService]
    },
    {
      provide: "DRIZZLE",
      useFactory: (pool: Pool): NodePgDatabase<typeof schema> => {
        return drizzle(pool, { schema: schema });
      },
      inject: ["DB_POOL"]
    }
  ],
  exports: ["DRIZZLE"]
})
export class DbModule implements OnApplicationShutdown {
  constructor(@Inject('DB_POOL') private readonly pool: Pool) {}

  async onApplicationShutdown(signal?: string) {
    await this.pool.end();
  }
}